Python + Flask:验证 json POST 请求非空的正确方法

问题描述 投票:0回答:2

首先,我对 python 很陌生。对于一个小项目,我必须实现一个网络服务,它可以接收 json 作为内容。我确实用 Flask 库实现了这个,到目前为止效果很好。 我现在遇到的唯一问题是错误处理。我会检查正确的内容类型,并将收到的 json 与方案进行比较。如果请求未通过这些检查,我将发送自定义 400 响应(引发 FailedRequest)。 我现在遇到的问题是,我不知道如何检查 request.json 是否为空。现在,当我发送具有正确内容类型但内容为空的请求时,我将得到系统生成的“错误请求”作为响应,而不是我的自定义响应。 如何检查 request.json 对象是否为空? request.json 是 None 不起作用......

或者我是否以错误的方式进行整个验证?

    #invoked method on a POST request
@app.route('/',methods = ['POST'])
def add():
    """
    This function is mapped to the POST request of the REST interface
    """
    print ("incoming POST")
    #check if a JSON object is declared in the header

    if request.headers['Content-Type'] == 'application/json; charset=UTF-8':
        print ("passed contentType check")
        print ("Json not none")
        print (request.get_json())
        data = json.dumps(request.json)
        #check if recieved JSON object is valid according to the scheme
        if (validateJSON(data)):
            saveToMongo(data)
            return "JSON Message saved in MongoDB"

    raise FailedRequest
python json post flask
2个回答
19
投票

只需检查

request.data
是否存在,
if(request.data): ...continue


0
投票

如果你想检查传入的有效负载(即 Flask API 中的

request.data
)是否为空,那么你可以尝试检查
request.content_length
是否为 0。这映射到
Content-Length
标头,它表示有效负载的大小,如下所示:

if request.content_length > 0:
  # do something
else:
  # return error

这里是官方 Flask API 链接,了解有关

request.content_length
属性的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.