【问题标题】:Flask Exception Handling and Message FlashingFlask 异常处理和消息闪烁
【发布时间】:2020-10-09 20:09:59
【问题描述】:

当某些条件不满足时,我的 python 代码会在控制台中注册一个错误。当不满足必要条件时,我试图在浏览器中显示相同的错误。为了说明这一点,考虑函数add_stuff 中非常基本的想法,它检查输入是否为int 类型。如果不是,则会在屏幕上打印一个错误。

以下简单的烧瓶应用程序和相应的模板文件工作,值错误实际上打印在屏幕上。但是,我试图“漂亮地打印”错误,这样它就不会打印丑陋的 jinga2 错误页面,而是停留在同一个 math.html 页面上,错误打印到屏幕上或可能重定向到一个有吸引力的页面没有拥挤的回溯等。

from flask import Flask, render_template, request, session, current_app
server = Flask(__name__)

def add_stuff(x,y):
    if isinstance(x, int) and isinstance(y, int):
        z = x + y
        return z
    else:
        raise ValueError("Not integers")       


@server.route('/math')
def foo():
    a = 1
    b = 15
    out = add_stuff(a,b)
    return render_template('math.html', out=out)  

if __name__ == '__main__':
    server.run(debug=True)

这是一个模板文件

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>

<body>

{{out}}

</body>
</html>

【问题讨论】:

    标签: python flask exception jinja2


    【解决方案1】:

    您可以捕获add_stuff 方法的异常以停止显示jinja2 错误页面。

    这里,我已经在flash 中包含了异常消息,并在模板中显示了它。如果出现异常,我不会在模板中显示out 值。

    from flask import Flask, flash, redirect, render_template, \
         request, url_for
    
    server = Flask(__name__)
    server.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
    
    
    def add_stuff(x,y):
        if isinstance(x, int) and isinstance(y, int):
            z = x + y
            return z
        else:
            raise ValueError("Not integers")       
    
    
    @server.route('/math')
    def foo():
        a = 1
        b = "some string"
        out = None
        try:
            out = add_stuff(a,b)
        except Exception as e:
            flash(str(e))
        if out is not None:
            return render_template('math.html', out=out)
        else:
            return render_template('math.html')
    

    math.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    
    <body>
        {% with messages = get_flashed_messages() %}
          {% if messages %}
            <ul>
            {% for message in messages %}
              <li>{{ message }}</li>
            {% endfor %}
            </ul>
          {% endif %}
        {% endwith %}
    
    {% if out %}
        {{out}}
    {% endif %}
    </body>
    </html>
    

    输出:

    您还可以根据要求对flash 消息进行分类(例如:错误、警告等)。你可以阅读the official documentation here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      相关资源
      最近更新 更多