Skip to content Skip to sidebar Skip to footer

Flask And Flask_login - Avoid Importing Flask_login From Main Code

I am currently coding up a simple web application using flask and flask_login. This is main.py: import flask import flask_login app = flask.Flask(__name__) login_manager = flask_

Solution 1:

create a file my_auth.py

# my_auth.py

import flask_login

login_manager = flask_login.LoginManager()

# create an alias of login_required decorator
login_required = flask_login.login_required

and in file main.py

# main.pyimport flask
from my_auth import (
    login_manager,
    login_required
)

app = flask.Flask(__name__)
login_manager.init_app(app)

@app.route('/')@login_requireddefindex():
    return"Hello World!"

Maybe this is what you want to achieve.

Solution 2:

I can confirm that Akshay's answer works.

While waiting for an answer, however, I've also found a workaround(?) that does not rely on using the decorator:

In main.py:

@SVS.route("/")
def index():
    if not my_auth.is_authenticated():
        return flask.redirect(flask.url_for('login'))

    return"Hello World!"

In my_auth.py:

defis_authenticated():
    return flask_login.current_user.is_authenticated

Post a Comment for "Flask And Flask_login - Avoid Importing Flask_login From Main Code"