3

I have a Flask RESTapi, which is used by multiple teams, and I would like to log the user statistics. The API doesn't have any user authentication mechanism because it is not needed in our corporate environment (it is hosted on internal server, so whoever can access it, he/she has rights to do it).

Still, I would like to know from where most of requests come. Sure, I can easily add a logger to database on each route, and save request.remote_addr, but I would like to do it before a concrete route is called (since it doesn't matter which route actually is called, I want user stats anyway); and so that it can be replicated to other Flask based API, and so there is no need to remember to add user-logger each time a route is created.

Well, the question is what part of Flask should I look for, in order to add my extra feature before the request is dispatched to a concrete route?

1 Answer 1

8

Flask has a before_request function and there you can access the current request with the global request object.

from flask import request

@app.before_request
def working():
    do_something_with_request(request)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.