Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: add usage statistics

Tags:

python

rest

flask

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?

like image 913
dgan Avatar asked Apr 17 '26 19:04

dgan


1 Answers

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)
like image 156
Robert Moskal Avatar answered Apr 19 '26 08:04

Robert Moskal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!