Skip to main content
 首页 » 编程设计

python之Web2Py实现自定义错误页面的一些疑惑

2025年05月04日40grandyang

我正在尝试为 web2py 中的自定义错误页面实现装饰器 根据海地 Todos 之一。引用 - http://web2py.com/AlterEgo/default/show/75

我试图将它作为一个模块保存在/modules 目录中,这样我就可以 将其导入 Controller 并适当放置装饰器。

我将错误处理装饰器保留为 /modules/onerror.py

然后像这样从 Controller 导入它,比如 (or.py)-

exec('from applications.%s.modules.onerror import onerror as onerror' 
                                                       % request.application) 

HTTP 对象在 onerror.py 中不可用,所以我做了一个 -

from gluon.http import * 

但后来我读到请求对象也不可用于 行中的装饰器 -

filename=os.path.join(request.folder,'views/errors/error%i.html'%status) 

我有些疑惑-

  1. /modules 目录是保存此类可重用组件的好地方吗?

  2. /modules 目录中的模块是否自动加载为 创建了新的 web2py 实例?如果是这样,我怎样才能访问它们 Controller ?

  3. 有没有办法将请求对象从 我的 Controller ?欢迎提供提示。

我当前的 onerror.py - http://paste.pocoo.org/show/186165/ 我尝试在 Controller 中使用的方式 - http://paste.pocoo.org/show/186167/

如果我以不明显的方式进行操作,请告诉我。

请您参考如下方法:

Solved通过 web2py 用户邮件列表。

you can also use: onerror = load_import('onerror').onerror

HTTP object wasn't available in onerror.py so i did a - from gluon.http import *

python 模块也是 web2py 中的普通 python 模块。他们只看到 python 关键字,除非你导入它们。 web2py 有 5 个特殊对象 (request, response, session, cache, T) 而你的应用有其他的 (db, 授权,crud)。因为它们在每次请求时都被实例化,所以它们 不能由模块导入,它们必须显式传递给 模块中的函数。请注意,虽然这很尴尬,但这就是 其他框架要求一直执行所有功能。 web2py 为模型和 Controller 保存这个。

But then I realized that the request object is also not available to the decorator as in the line - filename=os.path.join(request.folder,'views/errors/error %i.html'%status) I have some doubts - 1. Are the modules in the /modules directory automatically loaded as a new web2py instance is created? If so how can I access them?

没有。它们是普通的 python 模块。您必须导入它们才能使用 他们。

  1. Is there a way I can pass the request object to this decorator from my controller? Hints are welcome.

你需要一个元装饰器 def meta_decoration(something): def actual_decorator(f,something=something): 做你想做的() 返回 f() return decorator @meta_decorator(request) def function_to_be_decorated(): return dict() 反正你不需要这个 装饰器。查看 routes.examples.py 中的 routes_onerror。有 一个简单的方法来做你想做的事。