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?
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/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With