Reputation: 542
I'd like to use the Eve framework for creating a REST api and performing data validations. But I want to use the SQLAlchemy version of Eve with an rdbms back end. The Eve-SQLAlchemy documentation says nothing about how to do this.
For example, I will have a db table called 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)
Later I tell Eve about my database definitions:
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']})
The above works! If I try to store People
with a firstname other than 'Pete' I get a validation error. But it's a bit klunky to bolt on the validations after the schema definition like this. For instance, Eve picks up the max length 80 constraint from the People
table definition. It would be nice if the firstname
allowed constraint could be specified there too. Is there a recommended approach, and is it supported at all or liable to break in a future version.
Upvotes: 2
Views: 150
Reputation: 301
I've tried to clarify the relationship between DomainConfig
and Eve settings in the docs: https://eve-sqlalchemy.readthedocs.io/en/latest/tutorial.html#eve-settings :
You can do so using
DomainConfig
andResourceConfig
, 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
})
That said, if you actually have a constraint specified in your SQLAlchemy models that is not automatically translated into proper validation rules in Eve's schema definition, please open an issue!
Upvotes: 1