Skip to main content
 首页 » 编程设计

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

2024年11月24日11xiaohuochai

我想使用 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 模式定义中的正确验证规则,请提出一个问题!