I am developing a REST API in Flask. Some endpoints need to perform additional duties after the response is handled, but I would like to avoid using external processing queue or threads. One very convenient solution seems to be with WSGI Middleware and ClosingIterator, as outlined in this answer. However the handler of each point needs to know which endpoint handled the request, in order to perform their post-mortem duties.
One idea is to decorate my endpoints like this:
@app.route('/api/status/info', methods=['GET'])
def get_status_info():
@app.after_this_response('get_status_info')
def say_hi():
print('hi, unknown endpoint!')
return 'ok', 200
Instead of unknown endpoint
I would like to print get_status_info
. Is this possible?
Even better, if I write a generic @app.after_response
handler (as in another answer by the same author), can I determine in it which endpoint was used for handling the request?
EDIT: Trying to use flask.request.url_rule.endpoint
throws an exception:
RuntimeError: Working outside of request context.