0

Coming from Java development using Spark, I was able to attach custom attributes in the Request (servlet API) instance that gets passed to a handler.

Now, in Flask (Python), we get a global request object containing the details of the particular request. I have a @app.before_request decorator that needs to create a custom user object based on a given API token and attach it to the request to be accessed by target handlers.

@app.before_request
def check_api():
    if 'Authorization' in request.headers:
        token = request.headers['Authorization']
        if token:
            user = verify_and_get_user(token)
            request['user'] = user


@app.route('/resources/create', methods=['POST'])
def create_resource():
    print('- User with id %s created a resource' % request['user'].id)

How can I do something like the above, in a thread safe manner?

TheRealChx101
  • 1,468
  • 21
  • 38
  • I think you doesn't have to divide your code, you could do everything in the function below of the route and check if the required conditions are there, if doesn't, you can do a return an error – Axel Anaya Aug 04 '19 at 23:48
  • 2
    @AxelAnaya The reason why I added the *before* filter is because I know I will have a lot of route handlers, which will mean duplicate code. Instead, I'd rather have that method handle that. Also, it means I can return a `403` from it if the client did not provide a valid API token, without reaching the target handler. – TheRealChx101 Aug 04 '19 at 23:57

1 Answers1

2

You can store and share resources during a request by using the g global namespace object. More details here.

You will have to import it first: from flask import g.

You can find some usage examples here.