这是我的项目结构:
myproject
myproject
__init__.py
static
templates
views
__init.py__
home.py
venv
myproject.wsgi
requirements.txt
setup.py
这是我的__init__.py
:
from flask import Flask, request, Response, render_template
from myproject.views import home
app = Flask(__name__, static_folder="static", static_url_path='/static')
test_string = "Hello World!"
app.register_blueprint(home.home)
这是我的views/home.py
:
from flask import Flask, request, Response, Blueprint
import json
import requests
from myproject import test_string
home = Blueprint('home', __name__)
@home.route('/', methods=['GET'])
def test():
return(test_string)
当我访问该页面时,收到错误ImportError: Cannot import name test_string
。 Python 导入系统确实令人困惑,我不确定我在这里做错了什么,但我怀疑这是一个循环导入问题。
如何解决这个问题?
最佳答案
尝试移动,在 __init__.py
,行 from myproject.views import home
行后test_string = "Hello World!"
.
这样Python就会找到test_string名称。
要理解循环导入,当您执行 __init__.py
时,您必须“像解释器一样思考”口译员将:
- 执行
__init__.py
的第 1 行 - 执行该行暗示的所有代码(从 Flask 导入内容)
- 执行
__init__.py
的第 2 行 - 执行
views/home.py
的第 1 行(仅从 Flask 导入Blueprint
,因为它是唯一尚未导入的东西) - 执行
views/home.py
的第 2+3 行(导入json和请求) - 执行
views/home.py
的第 4 行 - 回到他在
__init__.py
中执行的操作并搜索名称test_string
这里引发了一个错误,因为他执行的内容不理解 test_string
。如果您将导入移至 test_string = "Hello World!"
的执行之后解释器将在命名空间中找到该名称。
这通常被认为是糟糕的设计,恕我直言,存储 test_string 的最佳位置是 config.py
文件,其中不执行从其他项目模块的导入,避免循环导入。
关于python - Flask 循环导入问题 - 将变量从 __init__.py 导入到 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57709127/