我必须在视图中强制定义模式,因为'missing'需要是动态的:
# ...
now = datetime.datetime.utcnow()
delta = datetime.timedelta(days=range)
schema = SchemaNode(Mapping())
schema.add(SchemaNode(Date(), name='to', missing=now))
schema.add(SchemaNode(Date(), name='from', missing=now - delta))
# ...
这太丑了。除了定义自定义类型之外还有更好的方法吗?
答案 0 :(得分:5)
@colander.deferred
def deferred_now(node, kw):
now = kw['now']
return now
@colander.deferred
def deferred_now_delta(node, kw):
return kw['now'] - kw['delta']
class MySchema(MappingSchema):
to = SchemaNode(Date(), missing=deferred_now)
frm = SchemaNode(Date(), missing=deferred_now_delta)
def aview(request):
schema = MySchema().bind(now=now(), delta=somedelta)