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?