Checkbox add option to view methods in before_request

Suppose I have an API in / api / something. The API requires api_key to be defined; it looks for request arguments and cookies. If it finds api_key, I want to pass api_key to the route methods, in this case something .

 @app.before_request def pass_api_key(): api_key = request.args.get('api_key', None) if api_key is None: api_key = request.cookies.get('api_key', None) if api_key is None: return 'api_key is required' # add parameter of api_key to something method @app.route('/api/something') def something(api_key): return api_key 

Is it possible?

Thanks in advance.

+7
source share
2 answers

One way to do this is to use flask.g . From the docs :

To exchange data that is valid for one request from only one function to another, the global variable is not good enough, because it will be split into streaming media. Flask provides you with a special object that ensures that it is valid only for the active request and which will return different values ​​for each request.

Set g.api_key to the value you want to store in before_request and read it in the route method.

g , like flask.request global, is what Flask and Werkzeug call a "contextual local" object - roughly speaking, an object that claims to be global, but actually provides different meanings to each request.

+9
source

This can be done using the url_value_processor decorator:

 @app.url_value_preprocessor def get_project_object(endpoint, values): api_key = values.get('api_key') if api_key is None: api_key = request.cookies.get('api_key', None) if api_key is None: raise Exception('api_key is required') values['api_key'] = api_key 

It can also be done at the core of Blueprint, so it only applies to views in the specified Blueprint.

0
source

Source: https://habr.com/ru/post/951953/


All Articles