gpt4 book ai didi

python - 在 Python Flask 框架中从模型到 View 到模板的 "bubble up"错误的正确方法

转载 作者:太空宇宙 更新时间:2023-11-03 15:22:52 25 4
gpt4 key购买 nike

在我的类中捕获错误并让错误消息从类“冒泡”到 View 并最终显示在模板上的正确方法是什么?

我现在遇到的问题是,我最终在我的模型和 View Controller 中捕获了两次相同的错误。这感觉不对。

这是一个例子:

模型/用户.py

class User(object):
errors = []

def __init__(self, string=None):
""" Initialize the user object
"""

#See if the input string is an e-mail address
try:
string_is_email = string.index('@')
except ValueError:
self.errors.append('Invalid e-mail address')
raise ValueError

查看/登录.py

@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':

email = request.form['email']
password = request.form['password']

#Catch invalid e-mails
try:
u = User(email)
except ValueError:
errors = u.errors

#In case the user hasn't POSTED
try:
errors = u.errors
except:
errors = None

return render_template('login.html', error=errors)

templates/login.html

    {% if error %}
<div class="error">
<ul>
{% for message in error %}
<li>{{ message }}</li>
{% endfor %}
</ul>
</div>

有没有更简洁的方法来做到这一点?

最佳答案

您可以使用 flash 直接将消息发送到模板,而不是那些错误 hack .此外,我会稍微修改一下:

class User(object):
def __init__(self, string):
""" Initialize the user object
"""

#See if the input string is an e-mail address
try:
string_is_email = string.index('@')
except ValueError:
raise ValueError('Invalid e-mail address')

@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':

email = request.form['email']
password = request.form['password']

#Catch invalid e-mails
try:
u = User(email)
except ValueError, e:
flash(e.message)

关于如何使用 flash,请查看文档:http://flask.pocoo.org/docs/patterns/flashing/ .

关于python - 在 Python Flask 框架中从模型到 View 到模板的 "bubble up"错误的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12271204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com