Junior — Middle
How can you count the number of HTTP requests in an application?
sobes.tech AI
Answer from AI
To count the number of HTTP requests in a Python application, you can use several approaches depending on the framework used.
For example, in Flask, you can create a simple middleware or use a decorator to count requests:
from flask import Flask, request
app = Flask(__name__)
request_count = 0
@app.before_request
def count_requests():
global request_count
request_count += 1
@app.route('/')
def index():
return f"Number of requests: {request_count}"
if __name__ == '__main__':
app.run()
If the application is more complex, you can use specialized monitoring tools, such as Prometheus with a metrics exporter, which automatically collect and visualize the number of requests.
You can also log requests and analyze logs to count them.