Simplest way to handle and display errors in a Python Pylons controller without a helper class
I have a class User() that throw exceptions when attributes are incorrectly set. I am currently passing the exceptions from the models through the controller to the templates by essentially catching exceptions two times for each variable.
Is this a correct way of doing it? Is there a better (but still simple) way? I prefer not to use any third party error or form handlers due to the extensive database queries we already have in place in our classes.
Furthermore, how can I "stop" the chain of processing in the class if one of the values is invalid? Is there like a "break" syntax or something?
Thanks.
>>> u = User()
>>> u.name = 'Jason Mendez'
>>> u.password = '1234'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "topic/model/user.py", line 79, in password
return self._password
ValueError: Your password must be greater than 6 characters
In my controller "register," I have:
class RegisterController(BaseController):
def index(self):
if request.POST:
c.errors = {}
u = User()
try:
u.name = c.name = request.POST['name']
except ValueError, error:
c.errors['name'] = error
try:
u.email = c.email = request.POST['email']
except ValueError, error:
c.errors['email'] = error
try:
u.password = c.password = request.POST['password']
except ValueError, error:
开发者_C百科 c.errors['password'] = error
try:
u.commit()
except ValueError, error:
pass
return render('/register.mako')
You could remove repetition from the code as a semi-measure:
class RegisterController(BaseController):
def index(self):
if request.POST:
c.errors = {}
u = User()
for key in "name email password".split():
try:
value = request.POST[key]
for o in (u, c):
setattr(o, key, value)
except ValueError, error:
c.errors[key] = error
u.commit() # allow to propagate (show 500 on error if no middleware)
return render('/register.mako')
Form Handling page from Pylons docs describes several simple approaches to form validating that you could adapt for your project.
class RegisterController(BaseController):
@save(User, commit=True)
# `save` uses filled c.form_result to create User()
@validate(schema=register_schema, form='register')
# `validate` fills c.form_errors, c.form_result dictionaries
def create(self):
return render('/register.mako')
Where validate()
is similar to Pylons validate()
decorator and save()
could be implemented as follows (using decorator module):
def save(klass, commit=False):
def call(action, *args, **kwargs):
obj = klass()
for attr in c.form_result:
if attr in obj.setable_attrs():
setattr(obj, attr, c.form_result[attr])
if commit:
obj.commit()
return action(*args, **kwargs)
return decorator.decorator(call)
精彩评论