我有python代码,可以在不满足某些条件时在控制台中注册错误。当不满足必要条件时,我试图在浏览器中显示这些相同的错误。为了说明,请考虑函数add_stuff
中的一个非常基本的想法,该函数检查输入是否为int
类型。如果不是这样,则会在屏幕上显示错误。
以下简单的flask应用程序和相应的模板文件可以正常工作,并且实际上在屏幕上显示了值错误。但是,我试图“漂亮地打印”错误,以便它不会打印难看的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>
答案 0 :(得分: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。