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.
To run your code before each Flask request, you can assign a function to the before_request() method, this can be done using decorators to make it a little simpler. This function will run before each and every endpoint you have in your application.
To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things.
Request. get_json (force=False, silent=False, cache=True)[source] Parses the incoming JSON request data and returns it. By default this function will return None if the mimetype is not application/json but this can be overridden by the force parameter.
By default, the Flask route responds to GET requests. However, you can change this preference by providing method parameters for the route () decorator. To demonstrate the use of a POST method in a URL route, first let us create an HTML form and use the POST method to send form data to the URL.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With