web2pyweb2py-modules

How to use HTTP() class in web2py module


I'm using a function in a web2py module which should raise an HTTP exception. For most functions (e.g. T) I do

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

But I can't do e.g. raise current.HTTP(...): I get

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

So is there any way to use HTTP() in a web2py module?


Solution

  • The best option is probably just to import HTTP in the module:

    from gluon.http import HTTP
    
    def f(x):
        raise HTTP(200, 'Hello')
    

    Alternatively, you can explicitly add the HTTP object to the current object. In a model file or in the relevant controller:

    current.HTTP = HTTP
    

    Then you will be able to access current.HTTP in any module where you import current.

    Finally, the entire web2py global environment is available via the current.globalenv dictionary, so in any module where you import current, you can do:

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

    web2py only adds the request, response, session, cache, and T objects directly to current, so if you want to access any other objects from the global environment, you must either add them explicitly or use current.globalenv.