【问题标题】:Flask circular import issue - import variables from __init__.py into viewsFlask 循环导入问题 - 将变量从 __init__.py 导入视图
【发布时间】:2019-08-29 11:25:12
【问题描述】:

这是我的项目结构

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 中有代码,请尽量避免在其中写入可以从其他地方导入的内容。将__init__.py 视为有关导入的图表中的叶子,它应该只导入和运行内容。

标签: python flask python-import importerror


【解决方案1】:

尝试在__init__.py 中将from myproject.views import home 行移动到test_string = "Hello World!" 行之后。

这样 Python 将找到 test_string 名称。

要理解循环导入,您必须“像解释器一样思考”,当您执行 __init__.py 时,解释器会:

  1. 执行__init__.py的第1行
  2. 执行此行所暗示的所有代码(从烧瓶中导入内容)
  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 文件,其中不执行从其他项目模块的导入,避免循环导入。

【讨论】:

  • 谢谢。这清楚了很多事情。它有效!所以最好的做法是将test_string移动到config.py并导入views.py?如果我在多个视图中需要相同的test_string,将它导入__init__.py 是否有意义?或者像@Arne 提到的那样,我不应该在__init__.py 中放任何东西?
  • 是的,正如@Arne 所说,最好设计一个项目,这样您的执行起点(在您的情况下为 init.py)只是其他模块代码的执行者,并且不是其他模块需要的代码“bin”。查看项目结构,在一个方向(从起点到模块和子模块)的导入越多越好。避免双向导入并将共享资源(例如您的 test_string)分组到其他人导入的“公共”模块中(即:您的所有视图)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 2015-07-30
  • 1970-01-01
  • 2017-05-17
  • 2014-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多