Is it an allowed pattern in Flask to modify request json data before the view functions (e.g. in a decorator)? Is it even possible? Imagining something like this:
from functools import wraps
from flask import request, current_app
def my_function_decorator(func):
@wraps(func)
def decorated_function(*args, **kwargs):
req = request.get_json()
# do something to calculate the new value
req["new key"] = "new value"
request.set_json(req)
return func(*args, **kwargs)
return decorated_function
The purpose is to have lat lon data geocoded from a third party service, based on address data that is sent to my service. Not sure if decorators are the right choice for this, or if it is before_request, or something else, or nothing at all.
I know this is a very old question, but there are people who coming here from google (like me). The answer would be:
from functools import wraps
from flask import Flask
from werkzeug.datastructures import ImmutableMultiDict
def my_function_decorator(func):
@wraps(func)
def decorated_function(*args, **kwargs):
http_args = request.args.to_dict()
http_args ['Shered Data'] = 'Hi!'
request.args = ImmutableMultiDict(http_args )
return func(*args, **kwargs)
return decorated_function
server = Flask(__name__)
@server.route('/')
@my_function_decorator
def index():
#Now, request.args contains your data
return 'It works! Shared data: %s' % (request.args.get('Shered Data'))
server.run(debug=True)