python - 使用 SQLAlchemy 版本的 Python Eve 进行验证

标签 python validation sqlalchemy eve

我想使用 Eve 框架来创建 REST api 和执行数据验证。但我想使用带有 rdbms 后端的 Eve 的 SQLAlchemy 版本。 Eve-SQLAlchemy 文档没有说明如何执行此操作。

例如,我将有一个名为 People 的数据库表:

# sql_schema.py
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import column_property, relationship

Base = declarative_base()

class People(Base):
    __tablename__ = 'people'
    id = Column(Integer, primary_key=True, autoincrement=True)
    firstname = Column(String(80))
    lastname = Column(String(120))
    fullname = column_property(firstname + " " + lastname)

后来我告诉 Eve 我的数据库定义:

from eve_sqlalchemy.config import DomainConfig, ResourceConfig
from sql_schema import People

# The default schema is generated using DomainConfig:
DOMAIN = DomainConfig({
    'people': ResourceConfig(People)
}).render()

# now I can stuff in my validations, a bit klunkily
DOMAIN['people']['schema']['firstname'].update({'allowed': ['Pete']})

以上有效!如果我尝试使用“Pete”以外的名字存储 People,我会收到验证错误。但是在这样的模式定义之后进行验证有点笨拙。例如,Eve 从 People 表定义中选取了最大长度 80 的约束。如果也可以在那里指定 firstname 允许的约束,那就太好了。是否有推荐的方法,它是否完全受支持或可能会在未来的版本中中断。

最佳答案

我试图在文档中阐明 DomainConfig 和 Eve 设置之间的关系:https://eve-sqlalchemy.readthedocs.io/en/latest/tutorial.html#eve-settings :

You can do so using DomainConfig and ResourceConfig, which will give you a default schema (DOMAIN dictionary) derived from your SQLAlchemy models. This is intended as a starting point and to save you from redundant configuration, but there's nothing wrong with customizing this dictionary if you need to!

# examples/simple/settings.py

# ...

# Even adding custom validations just for the REST-layer is possible:
DOMAIN['invoices']['schema']['number'].update({
    'min': 10000
})

就是说,如果您实际上在 SQLAlchemy 模型中指定了一个约束,但它没有自动转换为 Eve 模式定义中的正确验证规则,请提出一个问题!

关于python - 使用 SQLAlchemy 版本的 Python Eve 进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55084903/

相关文章:

python - 我以前从未见过 'class __proxy__',这是什么意思(我只见过像def __str__这样的)

python - 在 Pandas to_sql 中指定模式

sql - 如何强制 SQLAlchemy 包含重复的列?

python - 你如何在 Python 中递增文件名

python - 使用 Cython 传递 int 和 struct 包装 C 代码的最小示例

c++ - 正确数据类型的输入验证?

java - 如何降低圈复杂度?

validation - 验证 DevExpress GridControl 中的单元格

python - SQLAlchemy 查询具有关系计数的对象

python - pandas 中 header 和 Skiprow 的区别不清楚