Search code examples
pythonflaskdecoratorpython-decorators

import decorated and wrapped function to blueprints in flask


I have a login_required deecorated function, to manage page access.

My whole Flask project is in blueprints structured. Only main stuff is in the app.py. So I have palced the loqin_requiered function to app.py and want now to use it in my blueprint files.

app.py

from blueprint1 import blueprint_function1
app.register_blueprint(blueprint_function1)
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if "logged_in" in session:
            return f(*args, **kwargs)
        else:
            flash("Bu Sayfayi görüntülemek icin lütfen giris yapin", category="danger")
            return redirect(url_for("login"))
    return decorated_function

In my blueprint1.py I do the following:

from app import loqin_required

Then I get the following error: ImportError: cannot import name 'blueprint_function1'

How can I use this decorater in other files?


Solution

  • You import login_required in blueprint1.py:

    from app import login_required
    

    Now you also import blueprint1 in app.py:

    from blueprint1 import blueprint_function1
    

    These two modules import each other, it will cause Python Circular Dependency.

    To fix this, you can just create a new module to store your decorators. For example, create a decorators.py module aside from the app.py. Then change the import statement in blueprint1.py:

    from decorators import login_required