python - 您如何拥有不同的 View 来为 Pyramid 中的不同内容类型提供服务?

标签 python pyramid

文档似乎表明您可以为此使用“接受”view_config 参数,如下所示:

@view_config(
    route_name='data',
    request_method='POST',
    accept='application/json',
    renderer='json',
)
def json_post_view(self):
  ...

@view_config(
    route_name='data',
    request_method='POST',
    renderer='blah:templates/data.mako',
)
def form_post_view(self):
  ...

但是,实际上使用 wget 来发布到 url,就像这样:

wget -q -O - --post-file=data.json http://localhost:6543/data

或:

wget -q -O - --post-file=data.json --header="Content-type: application/json" http://localhost:6543/data

或使用浏览器发布到 url...

所有 结果相同;调用 json_post_view() View 。

我在这里做错了什么? accept 参数似乎根本没有做任何事情。

最佳答案

您想要使用谓词来分派(dispatch)到不同的 View ,正如您所做的那样。但是,accept 用于 Accept header ,该 header 用于形成您的响应。传入数据位于 Content-Type header 中, Pyramid 没有为其提供默认谓词。不过,您可以轻松编写自己的代码。

class ContentTypePredicate(object):
    def __init__(self, val, config):
        self.val = val

    def text(self):
        return 'content type = %s' % self.val
    phash = text

    def __call__(self, context, request):
        return request.content_type == self.val

config.add_view_predicate('content_type', ContentTypePredicate)

@view_config(content_type='application/json')
# ...

关于python - 您如何拥有不同的 View 来为 Pyramid 中的不同内容类型提供服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19783896/

相关文章:

python - 使用 contrib 模块安装 openCV

python - 如何在Python中使用另一个变量访问命名空间变量

python - 在 python 中导入时重定向 C 函数的标准输出时出现问题

python - 扩展 Pyramid 应用程序时出现 SQLalchemy 问题

python - Pyramid 登录和注销页面返回 404,应用程序的其余部分工作正常

python - 替换 if 语句的逻辑运算符

python - 检查用户是否具有 Pyramid (pylons 2)的权限?

rest - PUT 请求的 Pyramid 遍历

python - 设置 Pyramid Web 框架 | FCGI 共享主机

python - 在数据库中存储用户和密码