'Request' 对象没有属性 'get_json' Werkzeug

'Request' object has no attribute 'get_json' Werkzeug

我无法打印或读取我请求的 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 returns 将 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)