2

我必须在视图中强制定义模式,因为“缺失”需要是动态的:

    # ...
    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))
    # ...

这很丑陋。除了定义自定义类型之外,还有更好的方法吗?

4

1 回答 1

6

使用模式绑定

@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)
于 2012-05-13T02:23:16.010 回答