问题描述
我无法从我的请求中打印或读取json数据。 POST请求为application / json,发送的json有效。 知道为什么'get_json'不存在吗?
from werkzeug.wrappers import Request,Response
import json
@Request.application
def application(request):
data = request.get_json(force=True)
print(data)
return Response('Data Received')
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('localhost',5000,application)
将request.get_json
替换为request.get_data
会将json作为字符串(d'{\n"example": "here"\n}'
)
我已经确认我的Werkzeug安装是最新的。
解决方法
我能够解决自己的问题;
request
默认情况下没有get_json
,您需要对其进行子类化并自行添加。
这是一个例子:
from werkzeug.wrappers import BaseRequest,Response
from werkzeug.wrappers.json import JSONMixin
class Request(BaseRequest,JSONMixin):
'''Allow get_json with Werkzeug'''
pass
@Request.application
def application(request):
data = request.get_json(force=True)
print(data)
return Response('Data Received')
def __init__(self):
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('localhost',5000,application)