【问题标题】:Using '@notfound_view_config' in Pyramid with 'renderer'在 Pyramid 中使用 '@notfound_view_config' 和 'renderer'
【发布时间】:2013-03-29 11:56:43
【问题描述】:

Pyramid Docs - Using Hooks 中所述,使用@notfound_view_config 时,我无法渲染指定的模板。

views.py:

@notfound_view_config(renderer='templates/notfound.pt')
def notfound(request):
    return Response('Not Found, dude', status='404 Not Found')

模板/notfound.pt:

<html xmlns="http://www.w3.org/1999/xhtml"
      metal:use-macro="base">

<tal:block metal:fill-slot="content">

            <!-- Example row of columns -->
            <div class="row">
                <div class="span12">
                   <h1>Error:</h1>
                   <p>Uh, oh... you snagged an error:</p>
                   <pre>"${request}"</pre>

                   <p>You can return to the <a href="${request.application_url}">homepage</a> if you wish.</p>

                </div>
            </div>

</tal:block>
</html>

点击不存在的页面时,我在空白页面上看到消息“未找到,伙计”,但我希望看到我的模板“呃,哦......你遇到了一个错误!”后跟请求信息。

我怀疑我读错了:

notfound_view_config 构造函数接受大部分相同的 作为 pyramid.view.view_config 的构造函数的参数。有可能 在相同的地方使用,并且行为方式大致相同,除了 它总是注册一个未找到的异常视图而不是一个“正常” 查看。

一方面,我似乎应该能够将“renderer”指定为参数,因为它在 pryamid.view.view_config 中受支持。另一方面,听起来它总是加载[未找到异常视图][3],而不管“渲染器”选项。

真的,我的最终问题(和目标)是,当找不到页面时如何显示/呈现我的模板?

【问题讨论】:

  • source code 显然处理了一个渲染器,所以这应该只是工作。尝试更改视图中返回的 dict 以确保 100% 确定您没有混淆注册或重新启动。

标签: python pyramid


【解决方案1】:

Pyramid 中的渲染器-视图关系始终相同。如果您返回一个 Response 对象,那么您声明的渲染器将被绕过。这使您可以执行if submitted: return HTTPFound(location=...) else: return {} 之类的操作。如果您想影响响应对象并仍然使用您的渲染器,则返回所需的 dict 并变异 request.response,即用于所有渲染器的响应对象。

@notfound_view_config(renderer='templates/notfound.pt')
def notfound(request):
    request.response.status = 404
    return {}

【讨论】:

  • 非常感谢。做到了!
猜你喜欢
  • 1970-01-01
  • 2012-02-05
  • 1970-01-01
  • 1970-01-01
  • 2014-04-10
  • 2016-04-01
  • 2013-11-25
  • 1970-01-01
  • 2016-06-07
相关资源
最近更新 更多