Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't import LoginManager() in Flask

I am using Flask BluePrint in my applications and have to main parts: 1. Admin and 2. Public. When I try to import the loginManager to my views.py file I get the error 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

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

from app import lm

it raises ImportError.

ImportError: cannot import name lm

Can you please tell what might be the issue?

like image 407
Max Avatar asked May 25 '14 12:05

Max


1 Answers

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; any code in app.admin that then tries to address app.lm will fail.

Move blueprint imports down your module and lm will have been created already:

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.

like image 185
Martijn Pieters Avatar answered Nov 15 '22 17:11

Martijn Pieters