I'm struggling a bit with writing decorators to capture and modify requests within my flask application once the requests enters the application context and leaves the application context.
My function in a flask application looks like below. I want the control of requests at two points to add custom headers and params:
- before the request goes inside
get_foo
function and, - just before
requests.get('http://third-party-service/v1/api')
so I can attach any custom header or query param just before this request leaves the application.
@app.route('/my/v1/api')
def get_foo():
...
...
r = requests.get('http://third-party-service/v1/api')
...
...
return 'success!'
The former part I'm able to do using @app.before_request
decorator where I get control of the request once it reaches the get_foo
function.
@app.before_request
def before_request_callback():
method = request.method
path = request.path
print(method, path)
The latter part I'm not able to do. If I use @app.after_request
decorator, I get the control once the request has been process and I have got the response from http://third-party-service
.
I debugged sentry sdk and they're able to take control of the requests once the request leaves the application. I tried out to follow how they have implemented it by following their piece of code from the github repo (https://github.com/getsentry/sentry-python) but wasn't able to do so hence posting the question over here.
from Capture flask request when entering and leaving the application
No comments:
Post a Comment