我有一个类User(),当属性设置不正确时抛出异常。我目前通过控制器将模板中的异常传递给模板,实质上是为每个变量捕获两次异常。
这是一种正确的做法吗?有更好的(但仍然很简单)方式吗?我不希望使用任何第三方错误或表单处理程序,因为我们已经在我们的类中使用了大量的数据库查询。
此外,如果其中一个值无效,我如何“停止”类中的处理链?是否有“破解”语法或什么?
感谢。
>>> 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
在我的控制器“注册”中,我有:
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.errors['password'] = error
try:
u.commit()
except ValueError, error:
pass
return render('/register.mako')
答案 0 :(得分:0)
您可以从代码中删除重复作为一个半小节:
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')
来自Pylons docs的Form Handling页面描述了几种形式验证的简单方法,可以适应您的项目。
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')
其中validate()
类似于Pylons validate()
decorator和save()
可以如下实现(使用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)