SQLAlchemy 声明性模型的数据验证
我在 Web 应用程序中使用 CherryPy、Mako 模板和 SQLAlchemy。我有 Ruby on Rails 背景,正在尝试为我的模型设置一些数据验证。我无法找出确保“名称”字段在其他字段具有值时具有值的最佳方法。我尝试使用 SAValidation 但它允许我在所需列为空的情况下创建新行,即使我使用 列上的 validates_presence_of
。我一直在查看 WTForms 但这似乎涉及大量重复的代码 - 我已经使用以下命令设置了我的模型类表中的列,为什么我需要再次重复所有这些列只是为了说“嘿,这个需要一个值”?我来自“瘦控制器,胖模型”的心态,并且有一直在我的模型中寻找类似 Rails 的方法,例如 validates_presence_of 或 validates_length_of 。我应该如何验证我的模型接收到的数据,并确保验证失败时 Session.add
/Session.merge
失败?
I'm using CherryPy, Mako templates, and SQLAlchemy in a web app. I'm coming from a Ruby on Rails background and I'm trying to set up some data validation for my models. I can't figure out the best way to ensure, say, a 'name' field has a value when some other field has a value. I tried using SAValidation but it allowed me to create new rows where a required column was blank, even when I used validates_presence_of
on the column. I've been looking at WTForms but that seems to involve a lot of duplicated code--I already have my model class set up with the columns in the table, why do I need to repeat all those columns again just to say "hey this one needs a value"? I'm coming from the "skinny controller, fat model" mindset and have been looking for Rails-like methods in my model like validates_presence_of
or validates_length_of
. How should I go about validating the data my model receives, and ensuring Session.add
/Session.merge
fail when the validations fail?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
查看有关添加验证方法的文档。您可以添加一个“更新”方法,该方法采用 POST 字典,确保存在所需的键,并使用修饰的验证器来设置值(如果有任何问题,则会引发错误)。
Take a look at the documentation for adding validation methods. You could just add an "update" method that takes the POST dict, makes sure that required keys are present, and uses the decorated validators to set the values (raising an error if anything is awry).
我编写 SAValidation 的具体目的是在验证模型数据时避免代码重复。它对我们来说效果很好,至少对于我们的用例来说是这样。
在我们的测试中,我们有模型设置的示例< /a> 并测试以显示验证工作。
I wrote SAValidation for the specific purpose of avoiding code duplication when it comes to validating model data. It works well for us, at least for our use cases.
In our tests, we have examples of the model's setup and tests to show the validation works.
API Logic Server 为 SQLAlchemy 模型提供业务规则。这不仅包括多字段、多表验证,还包括多表验证。它是开源的。
API Logic Server provides business rules for SQLAlchemy models. This includes not only multi-field, multi-table validations, but multi-table validations. It's open source.
我最终还是使用了 WTForms。
I ended up using WTForms after all.