简体   繁体   English

flask和flask_login-避免从主代码导入flask_login

[英]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. 我目前正在使用flask和flask_login编写一个简单的Web应用程序。 This is main.py : 这是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 . 换句话说,我希望my_auth.py导入flask_login ,并且我希望main.py import my_auth ,而不必导入flask_login

The problem is with the @flask_login.login_required decorator. 问题出在@flask_login.login_required装饰器。 If I do not import flask_login from main.py , is it still possible to somehow "wrap" the main index() function with login_required ? 如果我不从main.py导入flask_login ,是否仍然可以通过login_required以某种方式“包装”主index()函数?

(I've actually asked a wrong question before, which may still be relevant: flask and flask_login - organizing code ) (实际上,我之前曾问过一个错误的问题,可能仍然很重要: flask and flask_login-组织代码

create a file my_auth.py 创建一个文件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

# 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. 我可以确认Akshay的答案有效。

While waiting for an answer, however, I've also found a workaround(?) that does not rely on using the decorator: 但是,在等待答案的同时,我还发现了一种不依赖使用装饰器的解决方法(?):

In main.py : 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 : my_auth.py

def is_authenticated():
    return flask_login.current_user.is_authenticated

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM