Search code examples
cherrypy

how to set the callable function parameters of 'before_handler' in cherrypy


def do_redirect(): raise cherrypy.HTTPRedirect("/login.html")

def check_auth(call_func): # do check ... if check_success(): return call_func() cherrypy.tools.auth = cherrypy.Tool('before_handler', check_auth) cherrypy.tools.auth.call_func = do_redirect

I want to set the function do_redirect as check_auth's parameter, but it throw the follow exception: TypeError: check_auth() takes exactly 1 argument (0 given)

but it can works if modify to follow code: def check_auth(call_func): # do check ... if check_success(): return cherrypy.tools.auth.call_func() cherrypy.tools.auth = cherrypy.Tool('before_handler', check_auth) cherrypy.tools.auth.call_func = do_redirect

how to set the callable function parameters of 'before_handler' in cherrypy?


Solution

  • There are a couple of way on setting the argument for a tool, take a look to this example:

    import cherrypy as cp
    
    
    def check_success():
        return False
    
    def do_redirect():
        raise cp.HTTPRedirect("/login.html")
    
    def fancy_redirect():
        raise cp.HTTPRedirect("/fancy_login.html")
    
    def secret_redirect():
        raise cp.HTTPRedirect("/secret_login.html")
    
    def check_auth(call_func=do_redirect):
        # do check ...
        if check_success():
            return
        call_func()
    
    cp.tools.auth = cp.Tool('before_handler', check_auth, priority=60)
    
    class App:
    
        @cp.expose
        @cp.tools.auth() # use the default
        def index(self):
            return "The common content"
    
        @cp.expose
        def fancy(self):
            return "The fancy content"
    
        @cp.expose
        @cp.tools.auth(call_func=secret_redirect) # as argument
        def secret(self):
            return "The secret content"
    
        @cp.expose
        def login_html(self):
            return "Login!"
    
        @cp.expose
        def fancy_login_html(self):
            return "<h1>Please login!</h1>"
    
        @cp.expose
        def secret_login_html(sel):
            return "<small>Psst.. login..</small>"
    
    
    cp.quickstart(App(), config={
        '/fancy': {
            'tools.auth.on': True,
            'tools.auth.call_func': fancy_redirect  # from config
        }
    })