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

Her*_*erb 4 python post json flask

首先,我对python很新.对于一个小项目,我必须实现一个websevice,可以接收json作为内容.我确实用烧瓶库实现了它,到目前为止工作正常.我现在唯一的问题是错误处理.我确实检查了正确的内容类型,并将收到的json与方案进行比较.如果请求未通过这些检查,我将发送自定义400响应(引发FailedRequest).我现在的问题是,我无法弄清楚,如何检查request.json是否为空.现在,当我发送一个具有正确内容类型但空内容的请求时,我会得到一个系统生成的"错误请求"作为响应,而不是我的自定义响应.如何检查request.json对象是否为空?request.json是没有工作....

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

    #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
Run Code Online (Sandbox Code Playgroud)

aks*_*hay 12

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