使用flask验证参数

时间:2018-03-08 15:32:40

标签: python flask flask-restful

我是Flask中的一个完全菜鸟,当我开始学习它时,我遇到了一些麻烦。具体来说,我想验证一些参数的存在和类型。

做了一些研究我发现了来自flask-restful的RequestParser类。

所以,这是我的方法:

data = {
   "x1" : 100,
   "x2" : 200,
   "x3" : 300
}

BASE_URL = "http://localhost:5000"
response = requests.post("{}/predict".format(BASE_URL), json = data)
response.json()

# {'x1': 100.0, 'x2': 200.0, 'x3': 300}

如果输入正常,这对我的测试代码很有用:

data = {
    "x1" : "a",
    "x2" : 200,
    "x3" : 300
}

但是,使用:

JSONDecodeError

我开始面对print(resnpose)。使用{"x1" : "x1 should be float"} 我看到API返回了代码400,但没有任何错误。我怎么能以字典的形式返回错误?例如:

Traceback (most recent call last):
  File "C:\Users\me\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\me\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\me\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\me\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\me\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\me\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1615, in full_dispatch_request
    return self.finalize_request(rv)
  File "C:\Users\me\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1630, in finalize_request
    response = self.make_response(rv)
  File "C:\Users\me\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1725, in make_response
    raise ValueError('View function did not return a response')
ValueError: View function did not return a response

错误追溯:

public SearchResponse getSearchResponse(SearchRequest searchRequest) {
    try {
        searchRequest.validate();
    } catch(VerifyException e) {
        ///some code to make errorResp
        return errorResp
    } catch(Exception e) {
        String key = searchRequest != null ? serchReqeust.getKey() : null;
        Logger.log("some text {}", key);
        //some code to make errorResp
        return errorResp;
    }
}

谢谢。

1 个答案:

答案 0 :(得分:0)

第一次误读这个问题的道歉。

所以按照http://flask-restful.readthedocs.io/en/0.3.5/reqparse.html#error-handling,你可以用这种方式处理它

parser = reqparse.RequestParser()
parser.add_argument(‘foo’, choices=(‘one’, ‘two’), help=’Bad choice: {error_msg}’)

然后,

{
"message": { "foo": "Bad choice: three is not a valid choice", }
}