python flask request hook
Question:
I want to be able to add some data into the request
variable in flask for all incoming requests
. Is there an easy way to hook into this without having to write this logic into each one of my endpoints?
Answers:
You may be looking for flask.Flask.before_request
.
Also you won’t necessarily be able to add data into the request
attributes form
and args
as they are immutable, consider using g
which is a thread local.
Example usage:
from flask import Flask, request, g
app = Flask(__name__)
@app.route('/')
def home():
return g.target + 'n'
@app.before_request
def before_req():
g.target = request.args.get('target', 'default')
if __name__ == '__main__':
app.run()
Usage:
$ curl 'http://localhost:5000/?target=value'
value
$ curl 'http://localhost:5000/?key=value'
default
I want to be able to add some data into the request
variable in flask for all incoming requests
. Is there an easy way to hook into this without having to write this logic into each one of my endpoints?
You may be looking for flask.Flask.before_request
.
Also you won’t necessarily be able to add data into the request
attributes form
and args
as they are immutable, consider using g
which is a thread local.
Example usage:
from flask import Flask, request, g
app = Flask(__name__)
@app.route('/')
def home():
return g.target + 'n'
@app.before_request
def before_req():
g.target = request.args.get('target', 'default')
if __name__ == '__main__':
app.run()
Usage:
$ curl 'http://localhost:5000/?target=value'
value
$ curl 'http://localhost:5000/?key=value'
default