我的自定义404页面不工作(Pyramid框架)
我想在我的Pyramid应用程序中显示一个漂亮的404页面,但一直搞不定。在看了很多关于这个主题的资料后,我在代码中加了类似下面的东西:
cfg.add_view( "Page_not_found_view", renderer="page_404.mak",
context=HTTPNotFound )
但是虽然我的*Page_not_found_view*处理器被调用了(我能看到它的运行记录),我还是看到那个可怜的“默认”404页面,而不是*我自己的page_404.mak*。有没有什么建议?
2 个回答
2
@chris-mcdonough 写的内容在大多数情况下应该是有效的。不过,如果你在视图函数中使用了 matchdict,并且想在没有匹配到任何内容时显示自定义的 404 页面,那么一定要抛出 HTTPNotFound
异常,而不是返回它。否则,你会看到默认的 404 页面。
示例:
from pyramid import httpexceptions
def my_page(self):
id = self.request.matchdict.get('id', None)
if not id:
raise httpexceptions.HTTPNotFound()
else:
# do whatever here
3
这里有一个示例应用,它使用了一个异常视图来捕捉Pyramid框架中出现的HTTPNotFound错误。这种错误会在找不到匹配的视图时被触发:
from waitress import serve
from pyramid.config import Configurator
from pyramid.response import Response
def hello_world(request):
return Response('<html><body>Hello world!</body></html>')
def notfound(request):
return Response('<html><body>Not found!</body></html>')
if __name__ == '__main__':
config = Configurator()
config.add_view(hello_world)
config.add_view(notfound, context='pyramid.httpexceptions.HTTPNotFound')
app = config.make_wsgi_app()
serve(app, host='0.0.0.0')
访问'/'会返回“你好,世界!”,而访问“/abc”或“/def”(或者其他任何找不到的地址)则会返回“未找到!”