Created
July 16, 2012 14:41
-
-
Save ties/3123086 to your computer and use it in GitHub Desktop.
Flask+AppEngine user decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Decorator that retrieves the current user from app engine and sets it on the wrapped function | |
Usage: | |
@user | |
[function definition] | |
or | |
@user("userobj") | |
def func(userobj, bar, baz) | |
""" | |
def user(func = None, var = "user"): | |
assert func is None or hasattr(func, '__call__') | |
def decorator(func): | |
@wraps(func) | |
def inject_user(*args, **kwargs): | |
user = users.get_current_user() | |
if not user: | |
return redirect(users.create_login_url(request.url)) | |
argspec = inspect.getargspec(func) | |
nkwargs = kwargs.copy() | |
nargs = list(args) | |
if var in argspec.args: # user is an arg | |
if argspec.args.index(var) is not 0: | |
raise AssertionError("{} should be the first function argument".format(var)) | |
nargs.insert(0, user) | |
elif argspec.keywords is not None: # varargs -> set it | |
nkwargs[var] = user | |
else: | |
raise AssertionError("user argument not found, make sure decorated function has {} as argument (or has **kwargs)".format(var)) | |
return func(*nargs, **nkwargs) | |
return inject_user | |
if func != None: | |
return decorator(func) | |
else: | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hacky :(