在查看功能之前(例如在装饰器中),在Flask中是否可以修改请求的json数据?可能吗想象这样的事情:
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
目的是根据发送到我的服务的地址数据对来自第三方服务的纬度数据进行地理编码。不确定装饰器是否是正确的选择,或者是before_request或其他,还是什么都没有。
答案 0 :(得分:3)
我知道这是一个非常老的问题,但是有些人是从Google来的(就像我一样)。答案将是:
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)