Skip to content

Instantly share code, notes, and snippets.

@ties
Created July 16, 2012 14:41
Show Gist options
  • Save ties/3123086 to your computer and use it in GitHub Desktop.
Save ties/3123086 to your computer and use it in GitHub Desktop.
Flask+AppEngine user decorator
"""
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
@ties
Copy link
Author

ties commented Jul 16, 2012

Hacky :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment