[英]Can't import LoginManager() in Flask
I am using Flask BluePrint in my applications and have to main parts: 1. Admin and 2. Public.我在我的应用程序中使用 Flask BluePrint,并且必须包含主要部分:1. Admin 和 2. Public。 When I try to import the loginManager to my views.py file I get the error ImportError: cannot import name lm
当我尝试将 loginManager 导入我的 views.py 文件时,出现错误ImportError: cannot import name lm
my folder structure is like:我的文件夹结构是这样的:
~/LargeApplication
|-- run.py
|-- config.py
|__ /env # Virtual Environment
|__ /app # Application Module
|-- __init__.py
|-- models.py
|-- /admin
|-- __init__.py
|-- views.py
|__ /templates
|-- ..
|__ ..
|__ .
I do initialize the LoginManager() in __ init__ .py file /app/__ init__ .py我确实在 __ init__ .py 文件 /app/__ init__ .py 中初始化了 LoginManager()
from flask.ext.login import LoginManager
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
and when I try to import lm in /app/admin/views.py当我尝试在 /app/admin/views.py 中导入lm时
from app import lm
it raises ImportError.它会引发 ImportError。
ImportError: cannot import name lm
Can you please tell what might be the issue?你能告诉我可能是什么问题吗?
You probably have a circular import.您可能有一个循环导入。 This is fine, but you need to take into account that you'll be working with modules that haven't yet completed all top-level instructions.
这很好,但您需要考虑到您将使用尚未完成所有顶级指令的模块。
If you have code like:如果你有这样的代码:
from flask.ext.login import LoginManager
from app.admin import admin_blueprint
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
then app.admin
will be imported before the lm = LoginManager()
line has executed;然后
app.admin
将在lm = LoginManager()
行执行之前导入; any code in app.admin
that then tries to address app.lm
will fail. app.admin
中的任何代码然后尝试解决app.lm
都将失败。
Move blueprint imports down your module and lm
will have been created already:将蓝图导入向下移动你的模块,
lm
将已经被创建:
from flask.ext.login import LoginManager
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
from app.admin import admin_blueprint
See the Circular Imports note in the 'Larger Applications' documentation section of the Flask manual.请参阅 Flask 手册的“大型应用程序”文档部分中的循环导入注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.