【问题标题】:Flask Redirect URL for page not found (404 error)找不到页面的 Flask 重定向 URL(404 错误)
【发布时间】:2019-06-16 01:09:16
【问题描述】:

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

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

我通过烧瓶网站找到了第二种方法,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()

【问题讨论】:

    标签: python flask error-handling url-routing


    【解决方案1】:

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

    @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
    

    【讨论】:

    • 我想知道如果有人尝试转到以我的网站结尾的错误 url,则重新路由所有可能的 url 的两种方法之间的区别。因此,我想将 .com/thisDoesNotExist 路由到我的主页,那么最好的方法是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2020-11-12
    • 2020-05-16
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多