python - 找不到页面的 flask 重定向URL(404错误)

标签 python flask error-handling url-routing

我想知道哪种方法更好地处理页面未找到错误404。因此,当有人尝试访问我的网站时,我找到了两种方法来重定向页面,但它们输入的是我没有为其建立路由的URL。第一种方法是构建一个错误处理程序,这样我可以这样做:

@app.errorhandler(404)
def internal_error(error):
    return redirect(url_for('index'))

我通过 flask 网站http://flask.pocoo.org/snippets/57/找到了第二种方法,它是这样的:
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    return redirect(url_for('index'))

区别在于,一个将处理错误,另一个将动态路由。但是,使用哪种更好?我真的不知道缺点是什么,在部署一个缺点之前,我想更好地了解它。

为了帮助这是我的基本代码:
@app.route('/', methods=["GET", "POST"])
def index():
  return render_template("HomePage.html")

if __name__ == "__main__":
  app.debug = True
  app.run()

最佳答案

我会说要处理您的情况,第二种方法很好,因为您需要处理不存在的路由

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    return redirect(url_for('index')) 

但是总的来说,两者都有不同的用例,比方说,您正在以不同的功能渲染多个模板,并且在渲染模板时遇到了异常。因此,要解决这种情况,您需要在所有方法中都实现异常处理。
此后,我们可以使用此功能注册异常并为用户创建自定义响应,而不是这样做并使其可读性和可伸缩性,请参阅以下内容:
# It will catch the exception when the Template is not found and
# raise a custom response as per the rasied exception
@app.errorhandler(TemplateNotFound)
def handle_error(error):
    message = [str(x) for x in error.args]
    status_code = 500
    success = False
    response = {
        'success': success,
        'error': {
            'type': error.__class__.__name__,
            'message': message
        }
    }
    return jsonify(response), status_code

# For any other exception, it will send the reponse with a custom message 
@app.errorhandler(Exception)
def handle_unexpected_error(error):
    status_code = 500
    success = False
    response = {
        'success': success,
        'error': {
            'type': 'UnexpectedException',
            'message': 'An unexpected error has occurred.'
        }
    }

    return jsonify(response), status_code

关于python - 找不到页面的 flask 重定向URL(404错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56615329/

相关文章:

c++ - 终止我的程序并让它输出我选择的错误消息的最佳方法是什么?

error-handling - Go 中更简洁的错误处理

python - 有 SimpleHTTPServer 的 Tornado 等效项吗?

python 记录 : is it possible to add module name to formatter

python - 有没有办法使用 Anaconda 作为与 npm 相同的包管理器?

python - Flask:model_form:AttributeError:类型对象 'Form'没有属性 'query'

python - flask / python 。从上传的文件中获取 mimetype

python - 返回工作日列表,从给定的工作日开始

python - 当线程完成时,如何更改 Flask 中渲染的模板?

asp.net-mvc - 我正在尝试下面给定的代码,但它显示错误 CS0051