Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to "bubble up" errors from a model, to a view, to a template in Python Flask framework

What's the proper way to catch errors in my class, and have error messages "bubble up" from the class, to the view, and finally be display on the template?

The problem I have now, is I end up catching the same errors twice, in both my models and view controllers. This doesn't feel right.

Here's an example:

model/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

view/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)

templates/login.html

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

Is there a cleaner way to do this?

like image 736
ensnare Avatar asked Dec 06 '25 02:12

ensnare


1 Answers

Instead of that errors hack, you can directly send the message to the template with flash. Furthermore, I would modify it a bit:

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)

On how to use flash, have a look into the documentation: http://flask.pocoo.org/docs/patterns/flashing/.

like image 98
dav1d Avatar answered Dec 08 '25 15:12

dav1d