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_login.LoginManager()
login_manager.init_app(app)
@app.route('/')
@flask_login.login_required
def index():
return "Hello World!"
The above code works. The problem arises because I want to separate authentication related code from the main flask application code. In other words, I want my_auth.py
that imports flask_login
, and I want main.py
to import my_auth
, and NOT have to import flask_login
.
The problem is with the @flask_login.login_required
decorator. If I do not import flask_login
from main.py
, is it still possible to somehow "wrap" the main index()
function with login_required
?
(I've actually asked a wrong question before, which may still be relevant: flask and flask_login - organizing code )
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.py
import flask
from my_auth import (
login_manager,
login_required
)
app = flask.Flask(__name__)
login_manager.init_app(app)
@app.route('/')
@login_required
def index():
return "Hello World!"
Maybe this is what you want to achieve.
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
:
def is_authenticated():
return flask_login.current_user.is_authenticated
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.