Объедините два Python-декоратора в один
Вот два декоратора, которые я хотел бы объединить, так как они очень похожи, разница в том, как обрабатывается не прошедший аутентификацию пользователь. Я предпочел бы иметь один единственный декоратор, который я могу вызвать с аргументом.
# Authentication decorator for routes
# Will redirect to the login page if not authenticated
def requireAuthentication(fn):
def decorator(**kwargs):
# Is user logged on?
if "user" in request.session:
return fn(**kwargs)
# No, redirect to login page
else:
redirect('/login?url={0}{1}'.format(request.path, ("?" + request.query_string if request.query_string else '')))
return decorator
# Authentication decorator for routes
# Will return an error message (in JSON) if not authenticated
def requireAuthenticationJSON(fn):
def decorator(**kwargs):
# Is user logged on?
if "user" in request.session:
return fn(**kwargs)
# No, return error
else:
return {
"exception": "NotAuthorized",
"error" : "You are not authorized, please log on"
}
return decorator
И в настоящее время я использую эти декораторы для определенных маршрутов, например
@get('/day/')
@helpers.requireAuthentication
def day():
...
@get('/night/')
@helpers.requireAuthenticationJSON
def night():
...
Я бы предпочел это:
@get('/day/')
@helpers.requireAuthentication()
def day():
...
@get('/night/')
@helpers.requireAuthentication(json = True)
def night():
...
Я на Python 3.3 с использованием фреймворка Bottle. Можно ли делать то, что я хочу? Как?