3

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

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

这是一个例子:

模型/用户.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)

模板/login.html

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

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

4

1 回答 1

4

您可以使用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/

于 2012-09-04T21:00:02.483 回答