How to use the keyword arguments in Flask-RESTless

2019-08-05 07:59发布

问题:

Me and a buddy have been reading through the docs for Flask-RESTless and it says:

The arguments to the preprocessor and postprocessor functions will be provided as keyword arguments, so you should always add **kw as the final argument when defining a preprocessor or postprocessor function.

but it doesn't specify how we can use these keyword argument to pass info to the pre- or postprocessor. Can anyone tell us how to do this?

Our create_api looks like this right now:

create_api(Foo,
           methods=['GET', 'POST', 'PUT', 'DELETE'],
           collection_name='p',
           url_prefix='/api/v1',
           primary_key='uid',
           exclude_columns=['id'],
           preprocessors={
              'POST': [authenticate, validation_preprocessor],
              'GET_SINGLE': [authenticate],
              'GET_MANY': [authenticate],
              'PUT_SINGLE': [authenticate, validation_preprocessor],
              'PUT_MANY': [authenticate, validation_preprocessor],
              'DELETE': [authenticate]
           })

def validation_preprocessor(data=None, **kw):
    # Do stuff
    pass

What we want to do is use **kw in validation_preprocessor for our own values.

回答1:

From reading the docs, you don't pass data to the pre-processor, you are the pre-processor and data is passed to you.

The exact format of the data depends on the specific method:

https://flask-restless.readthedocs.org/en/latest/customizing.html#request-preprocessors-and-postprocessors

The preprocessors and postprocessors for each type of request accept different arguments. Most of them should have no return value (more specifically, any returned value is ignored)....Those preprocessors and postprocessors that accept dictionaries as parameters can (and should) modify their arguments in-place.

You don't use the *kw directly, it's just there to make your code forwards compatible with Flask-RESTLess so if they decided to update the API and send a different set of parameters to your function, it won't break.

In your particular example, you would just edit the data dictionary and since Python variables are pass by assignment, once you edit it, it's edited for the rest of the chain.

def validation_preprocessor(data=None, **kw):
    if data:
        data["foobar"] = "rarr I'm a dinosaur"

I personally think that's confusing and not how I would expect things to work, but I assume they had a reason for it.