Skip to content

Instantly share code, notes, and snippets.

@aodag
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aodag/6a25a55d45c543b0e83a to your computer and use it in GitHub Desktop.
Save aodag/6a25a55d45c543b0e83a to your computer and use it in GitHub Desktop.
colanderでDB絡みのチェックをかけるバリデータの検討

使い方の想定

schema.bind(query=DBSession.query(Person).filter(Person.gender=='male')
           col=Person.first_name + " " + Person.last_name)
import colander as c
from . import validators
@c.deferred
def bind_queryable(node, kw):
return validators.QueryableValidator(kw["query"], kw["col"])
class PersonSchema(c.Schema):
gender = c.SchemaNode(c.String(), validator=OneOf('male', 'female'))
organization = c.SchemaNode(c.Integer, validator=bind_queryable))
class QueryableValidator(object):
def __init__(self, query, col):
self.query = query
self.col = col
def __call__(self, node, value):
if not self.query.filter(self.col==value).exists():
raise Invalid
@shimizukawa
Copy link

フィールド毎にbindしたい場合

s = PersonSchema()
s['organization'] = s['organization'].bind(
    query=DBSession.query(Person).filter(Person.gender=='male')
    col=Person.first_name + " " + Person.last_name)
)
s['other'] = s['other'].bind(....)
obj = s.deserialize(request.json)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment