Skip to content

Instantly share code, notes, and snippets.

@Curiouspaul1
Forked from pcdinh/decorators.py
Created August 17, 2019 01:05
Show Gist options
  • Save Curiouspaul1/356fbd3b12a36798a85b69f040a908dd to your computer and use it in GitHub Desktop.
Save Curiouspaul1/356fbd3b12a36798a85b69f040a908dd to your computer and use it in GitHub Desktop.
Flask login_required decorator
from flask import request, g
from functools import wraps
def login_required(f=None, url="public.login", next=None):
"""
Check if user is logged or redirect to a certain page.
By default go to public login.
"""
def outer_decorator(decorated_fn):
"""
Takes the decorated function <fn>.
"""
@wraps(decorated_fn)
def inner_fn(*ted_args, **ted_kw):
"""
Takes the decorated function params <ted_args> and <ted_kw>.
<next> workaround thanks to <mitsuhiko>:
> that does not work:
> if next is None:
> next = request.url
> instead you need to do
> the_next = next
. if the_next is None:
. the_next = request.url
> and then use the_next
> or some other variable
> next is from an outer scope
> overriding that does not work in python 2 and would not be threadsafe in python 3
> yay!
> but why does "url" don't need that?
> you are not overriding url
> if you would do ``url += "foo"`` it would fail too
"""
_next = next
if _next is None:
_next = request.url
## Redirect conditions
if not isinstance(g.user, dict):
return redirect_to(url, next=_next)
return decorated_fn(*ted_args, **ted_kw)
return inner_fn
# <f> is None when this deco is called with params
# if f is not None:
if callable(f):
return outer_decorator(f)
return outer_decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment