gpt4 book ai didi

Python + flask : Correct way to validate that json POST request is non-empty

转载 作者:太空狗 更新时间:2023-10-30 01:50:59 30 4
gpt4 key购买 nike

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

最佳答案

只需检查 request.data 是否存在,if(request.data): ...continue

关于Python + flask : Correct way to validate that json POST request is non-empty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29346131/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com