gpt4 book ai didi

python - 使用 Flask 验证参数

转载 作者:行者123 更新时间:2023-12-01 23:36:09 25 4
gpt4 key购买 nike

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

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

所以,这就是我的方法:

@app.route("/", methods=['POST'])
def testing():

if request.method == 'POST':
try:
parser = reqparse.RequestParser(bundle_errors=True)
parser.add_argument('x1', type=float, help="x1 must be float")
parser.add_argument('x2', type=float, help="x2 must be float")
parser.add_argument('x3', choices=(1,2), help="x3 must be binary")

return jsonify({'test': 'ok})
except:
pass

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

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) 我看到 API 返回代码 400,但没有任何错误。如何以字典的形式返回错误?例如:

{"x1" : "x1 should be float"}

错误回溯:

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

谢谢。

最佳答案

对于第一次误读问题表示歉意。

因此,根据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", }
}

关于python - 使用 Flask 验证参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49176837/

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