Flask 循环导入问题 - 将 __init__.py 中的变量导入视图

Flask circular import issue - import variables from __init__.py into views

这是我的项目结构:

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 名称。

要理解循环导入,您必须 "think like the interpreter",当您执行 __init__.py 时,解释器将:

  1. 执行 __init__.py
  2. 的第 1 行
  3. 执行这一行暗示的所有代码(从烧瓶中导入东西)
  4. 执行__init__.py
  5. 的第2行
  6. 执行 views/home.py 的第 1 行(仅从 flask 导入 Blueprint,因为它是唯一尚未导入的东西)
  7. 执行 views/home.py 的第 2+3 行(导入 json 和请求)
  8. 执行views/home.py
  9. 的第4行
  10. 回到他在__init__.py执行的并搜索名字test_string

这里报错,因为他执行的没有理解test_string。如果在 执行 test_string = "Hello World!" 之后移动导入 ,解释器将在命名空间中找到这个名称。

尽管这通常被认为是糟糕的设计,恕我直言,存储 test_string 的最佳位置是 config.py 文件,其中不执行从其他项目模块的导入,避免循环导入。