python - 为 colander.SchemaNode 动态定义 'missing'

标签 python pyramid

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

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

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

最佳答案

使用schema binding .

@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)

关于python - 为 colander.SchemaNode 动态定义 'missing',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10567286/

相关文章:

python - Pyramid/wsgi os.environ 后门的安全隐患?

python - 如何使用 Pyramid 访问 Plone 生成并保存在 ZODB 上的数据?

python - 子区间的平均值 Python

python - 将numpy数组转换为2d数组

python - 手动安排Azure中Postgresql的备份?

python - 如何在python中将分割图像叠加在主图像之上

Python 数组求和与 MATLAB

python - 在 Tornado 下运行 Pyramid WSGI 应用程序

python - 将 python 列表存储到数据库的最佳方法?

python - 更改 session cookie的超时时间是否存在安全风险?