【问题标题】:Complaining not a "package" though there is a __init__.py file in the folder尽管文件夹中有一个 __init__.py 文件,但抱怨不是“包”
【发布时间】:2021-06-21 13:19:57
【问题描述】:

以下是我的代码层次结构。

我正在尝试为我的项目“UIGenerator”创建一个包,但它给了我以下错误。

traceback (most recent call last):
  File "run.py", line 1, in <module>
    from UIGenerator import app
  File "/Users/______/Desktop/UIGenerator/UIGenerator/__init__.py", line 2, in <module>
    from site.routes import site
ModuleNotFoundError: No module named 'site.routes'; 'site' is not a package

这是 run.py 的代码 =>

from UIGenerator import app

@app.route('/')
def test_connection():
    return "<h1>Connected<h1>"

if __name__ == '__main__':
    app.run(debug=True)

site =&gt;__init__.py 文件和site=&gt;routes.py 中没有任何内容,我有一些示例代码要测试-

from flask import Blueprint

site = Blueprint('site', __name__)

@site.route('/site')
def site():
    return "this is test for site package"

以下是我为 UIGenerator 的 init.py 文件编写的代码 =>

from flask import Flask
from site.routes import site

def getApp():
    app = Flask(__name__)
    app.register_blueprint(site)
    return app

app = getApp()

谁能给我一点线索,拜托。

【问题讨论】:

    标签: python flask package blueprint


    【解决方案1】:

    解决此问题的一种方法是使用您的文件构建 Python 包,like outlined here。如果你想扩大这个项目,从长远来看这会更好,allow you to declare things in init

    话虽如此,我认为您可以通过移动这段代码来使您的设置正常工作

    def getApp():
        app = Flask(__name__)
        app.register_blueprint(site)
        return app
    
    app = getApp()
    

    暂时到run.py文件。

    【讨论】:

    • 谢谢你的参考,虽然它没有解决我的问题。
    【解决方案2】:

    所以,这是我从另一篇文章中发现的。在我的站点 => 路由中,我声明了一个名为 site 的全局蓝图,后来我创建了一个 site() 函数,它以某种方式掩盖了我的站点蓝图。如果我只是重命名了站点方法名称,它就可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多