Skip to main content
 首页 » 编程设计

python之Pylons:如何编写自定义 404 页面

2025年05月04日7webabcd

所以这个问题has been asked before ,但没有详细回答。

我想覆盖默认的 Pylons 错误页面以制作一个更好的自定义页面。我已经覆盖了 error.py 中的 Controller ,如下所示:

def document(self): 
    """Render the error document""" 
    resp = request.environ.get('pylons.original_response') 
    content = literal(resp.body) or cgi.escape(request.GET.get('message', '')) 
    custom_error_template = literal("""\ 
    # some brief HTML here 
    """) 
    page = custom_error_template % \ 
        dict(prefix=request.environ.get('SCRIPT_NAME', ''), 
             code=cgi.escape(request.GET.get('code', str(resp.status_int))), 
             message=content) 
    return page 

这工作正常。我现在想做的是使用templates目录下的模板,这样404页面就可以继承我常用的布局模板,CSS等。

(我知道这对于 500 错误是个坏主意 - 在我使用模板而不是文字之前,我会检查 error.py 代码是 404。)

那么,问题来了。如何定义 custom_error_template 以指向我的模板,而不是文字?

请您参考如下方法:

您应该能够使用render 方法(从yourapp.lib.base 导入它,并使用return render('/path/to/error/模板')。