【问题标题】:Validations with the SQLAlchemy version of Python Eve使用 Python Eve 的 SQLAlchemy 版本进行验证
【发布时间】:2019-03-10 05:58:55
【问题描述】:

我想使用 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 允许的约束也可以在那里指定,那就太好了。是否有推荐的方法,是否完全支持或可能在未来的版本中中断。

【问题讨论】:

    标签: python validation sqlalchemy eve


    【解决方案1】:

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

    您可以使用DomainConfigResourceConfig 执行此操作,这 会给你一个默认的模式(DOMAIN字典)从你的 SQLAlchemy 模型。这旨在作为一个起点并为您节省 来自冗余配置,但自定义它没有错 如果你需要字典!

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

    也就是说,如果您实际上在 SQLAlchemy 模型中指定了一个约束,该约束没有自动转换为 Eve 架构定义中的正确验证规则,请打开一个问题!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多