Reputation: 15
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?
Upvotes: 1
Views: 597
Reputation: 5741
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
}
})
Upvotes: 1
Reputation: 2453
Try this
cherrypy.tools.auth = HandlerWrapperTool(newhandler=auth_fn)
or
class AuthHandler(Tool):
def __init__(self, auth_fn):
self._point = 'before_handler'
self._name = 'auth_handler'
self._priority = 10
self._auth_fn = auth_fn
def callable(self):
# implementation
Upvotes: 1