belin
belin

Reputation: 5

How to create a decorator in flask?

what can I do to replace if and else. I will need this condition in several places.

@blueblue.route('/', methods=['GET', 'Post'])
# 
def deactivate_trainer():
    if current_user.is_authenticated and current_user.account_type == 'su':

        form = ActivateDeactivateTrainer
        return render_template('x.html', form=form)
    
    else:
        return redirect(url_for('blueblue.login'))

Upvotes: 0

Views: 624

Answers (2)

amirreza
amirreza

Reputation: 39

You must use functools.wraps() to handle this in flask
This is how i edited your code:

from functools import wraps
from flask import redirect, url_for
def my_decorator(function):
    @wraps(function)
    def decorated_function(*args, **kwargs):
        if current_user.is_authenticated and current_user.account_type == 'su':
            return function(*args, **kwargs)
        else:
            return redirect(url_for('blueblue.login'))

and you can use your decorator this way

@blueblue.route('/', methods=['GET', 'Post'])
@my_decorator
def deactivate_trainer():
    #...

also you can see Flask documentation for more information

Upvotes: 1

Shrey Tripathi
Shrey Tripathi

Reputation: 218

To authenticate the user while login, you could do something like this:

from flask import redirect, render_template, request, session
from functools import wraps

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not (current_user.is_authenticated and current_user.account_type == 'su'):
            return redirect(url_for('blueblue.login'))
        return f(*args, **kwargs)
    return decorated_function

This defines a separate decorator for logging in users.
Using the decorator is as simple as including a simple line:

@blueblue.route('/', methods=['GET', 'Post'])
@login_required
def deactivate_trainer():
    form = ActivateDeactivateTrainer
    return render_template('x.html', form=form)

And voila! You don't have to use those annoying if-else conditions ever again!

Visit here for more info.

Upvotes: 2

Related Questions