python-3.x - Flask - 中止时的自定义错误消息

标签 python-3.x flask

我希望能够在 Flask 中使用 abort() 显示自定义错误消息。我遇到了一个我遇到麻烦的异常情况。我的代码如下。

from flask import Flask, abort, jsonify, make_response, request

app = Flask(__name__)

@app.errorhandler(400)
def custom400(error):
    return make_response(jsonify({'message': error.description}), 400)

@app.route('/test', methods=['POST'])
def test():
    abort(400, 'custom error message')

if __name__ == '__main__':
    app.run()

上面的代码可以工作,但如果我尝试访问任何表单数据,行为会有所不同,因为我无法访问自定义错误消息。

def test():
    a = request.form['some_value']
    abort(400, 'custom error message')

如何避免这种情况?这是 Flask 错误吗?

注:以上代码取自how to get access to error message from abort command when using custom error handler

最佳答案

错误没有描述,因为您没有在 POST 正文中设置 some_value,所以 400 错误来自 request.form.__getitem__ - 更改第一行测试 a = request.form.get('some_value') 并且你的 abort 错误将被抛出。

关于python-3.x - Flask - 中止时的自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35209886/

相关文章:

python - peewee.IntegrityError : NOT NULL constraint failed

python - flask 和 WTForms : How to make a form with multiple submit buttons?

postgresql - 使用 Flask 将 Docker 容器连接到 App Engine 中的 PostgreSQL 时出现问题

python-3.x - 为什么 Atom 不使用我在 Atom 终端中激活的 virtualenv?

python - 如何将嵌套的字典列表展平为多行?

python - 我可以在Python中使用带有随机错误处理值的except函数吗?

python - Flask 内容配置 header 中的 Unicode

python - 如何 pickle 包含模块和类的字典?

python - 使用 urllib 而不是 http.client 登录网站

docker - 无法更改 nginx.conf 文件