python - Flask 循环导入问题 - 将变量从 __init__.py 导入到 View 中

标签 python flask python-import importerror

这是我的项目结构:

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 时,您必须“像解释器一样思考”口译员将:

  1. 执行 __init__.py 的第 1 行
  2. 执行该行暗示的所有代码(从 Flask 导入内容)
  3. 执行 __init__.py 的第 2 行
  4. 执行 views/home.py 的第 1 行(仅从 Flask 导入 Blueprint,因为它是唯一尚未导入的东西)
  5. 执行 views/home.py 的第 2+3 行(导入json和请求)
  6. 执行 views/home.py 的第 4 行
  7. 回到他在 __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/

相关文章:

python - Keras 自定义缩放层

python - 如何在 Python 中使用 OpenCV 从 POST 请求加载视频?

python - 如何在 Flask 中使用 Flot 图表?

python - 如何使 Python 模块的 __init__.py 将其 help() 委托(delegate)给同级文件?

python - `import module` 是否比 `from module import function` 更好的编码风格?

python - Numpy:通过组合先前数组的子集来创建新数组

python: skimage.transform.AffineTransform 旋转中心

python - 在 Python 中覆盖命名空间

python - ValueError : x and y must have the same first dimension

python - 如何加速 Flask 应用程序的 JSON 速度?