如何在 web2py 模块中使用 HTTP() class

How to use HTTP() class in web2py module

我正在 web2py 模块中使用一个函数,它应该会引发 HTTP 异常。对于大多数函数(例如 T)我做

from gluon import current
def f(x):
    return current.T(x)

但是我做不到raise current.HTTP(...):我得到

<type 'exceptions.AttributeError'> 'thread._local' object has no attribute 'HTTP'

那么有什么方法可以在 web2py 模块中使用 HTTP() 吗?

最好的选择可能只是在模块中导入 HTTP:

from gluon.http import HTTP

def f(x):
    raise HTTP(200, 'Hello')

或者,您可以显式地将 HTTP 对象添加到 current 对象。在模型文件或相关控制器中:

current.HTTP = HTTP

然后您将能够在导入 current.

的任何模块中访问 current.HTTP

最后,整个 web2py 全局环境可通过 current.globalenv 字典获得,因此在导入 current 的任何模块中,您可以:

raise current.globalenv['HTTP'](200, 'Hello')

web2py 仅将 requestresponsesessioncacheT 对象直接添加到 current,因此如果你想从全局环境访问任何其他对象,你必须显式添加它们或使用 current.globalenv.