“请求”对象没有属性“ get_json”

问题描述

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...