How to create Flask (Python) Login Required Decorator

  • Posted on: 4 March 2015
  • By: oon
Flask Login Required Decorator

Python has interesting feature called function decorators. Implement it using function functools.wraps().

a decorator is a function that returns a function [1].

from functools import wraps
from flask import g, request, redirect, url_for

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if g.user is None:
            return redirect(url_for('login', next=request.url))
        return f(*args, **kwargs)
    return decorated_function

This is how we use it.

@app.route('/secret_page')
@login_required
def secret_page():
    pass

You can make cache and template from decorator, please refer to [1].

[1]http://flask.pocoo.org/docs/0.10/patterns/viewdecorators/

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.