【问题标题】:Correct way to "bubble up" errors from a model, to a view, to a template in Python Flask framework在 Python Flask 框架中从模型、视图、模板“冒泡”错误的正确方法
【发布时间】:2012-09-04 20:53:55
【问题描述】:

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

我现在遇到的问题是,我最终在模型和视图控制器中都发现了两次相同的错误。这感觉不对。

这是一个例子:

模型/user.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

查看/login.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)

模板/login.html

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

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

【问题讨论】:

  • 我认为你不需要 models/user.py 中的 try/except ......因为如果没有发现错误会自动冒泡
  • 我确实这样做是为了设置错误消息。如果我没有那个 try/except ,我必须将消息放在视图中。但是,如果我在另一个视图中使用该类,我将不得不复制代码

标签: python error-handling flask


【解决方案1】:

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

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/

【讨论】:

  • 所以有必要在两个地方(在类中,在控制器中?)捕获相同的错误
  • 不,但这是最有意义的,这段代码允许您使用不同的消息抛出不同的ValueErrors,您只需捕获它们一次。
猜你喜欢
  • 1970-01-01
  • 2015-08-04
  • 2011-11-09
  • 1970-01-01
  • 2011-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多