找不到页面的烧瓶重定向URL(404错误)

时间:2019-06-16 01:09:16

标签: python flask error-handling url-routing

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

from multiprocessing import Pool

我通过烧瓶网站http://flask.pocoo.org/snippets/57/找到了第二种方法,就像这样:

AttributeError: Can't pickle local object 'kl_ucb.act.<locals>.max_q_min'

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

为了帮助这是我的基本代码:

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

1 个答案:

答案 0 :(得分: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
相关问题