问题
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)
回答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.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.
回答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:
def is_authenticated():
return flask_login.current_user.is_authenticated
来源:https://stackoverflow.com/questions/38930978/flask-and-flask-login-avoid-importing-flask-login-from-main-code