Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

python - ImportError: cannot import name

I have two files app.py and mod_login.py

app.py

from flask import Flask
from mod_login import mod_login

app = Flask(__name__)
app.config.update(
    USERNAME='admin',
    PASSWORD='default'
)

mod_login.py

# coding: utf8

from flask import Blueprint, render_template, redirect, session, url_for, request
from functools import wraps
from app import app

mod_login = Blueprint('mod_login', __name__, template_folder='templates')

And python return this error:

Traceback (most recent call last):
  File "app.py", line 2, in <module>
    from mod_login import mod_login
  File "mod_login.py", line 5, in <module>
    from app import app
  File "app.py", line 2, in <module>
    from mod_login import mod_login
ImportError: cannot import name mod_login

If I delete from app import app, code will be work, but how I can get access to app.config?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that you have a circular import: in app.py

from mod_login import mod_login

in mod_login.py

from app import app

This is not permitted in Python. See Circular import dependency in Python for more info. In short, the solution are

  • either gather everything in one big file
  • delay one of the import using local import

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...