首页 > 解决方案 > Python Flask 蓝图 - ImportError:无法导入名称应用程序

问题描述

我正在完成关于烧瓶蓝图的教程,第一步是下载烧瓶并打印初始的“Hello World”。但是,当我尝试运行初始 run.py 文件时,出现以下错误:

Traceback (most recent call last):
File "run.py", line 1, in <module>
    from site import app
ImportError: cannot import name 'app' from 'site' (/Users/kyle/anaconda3/lib/python3.7/site.py)

我的文件结构是:

website/
     run.py
     site/
        __init__.py

运行.py

from site import app

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

__init__.py

from flask import Flask

app = Flask(__name__)


@app.route('/')
def root():
    return "Hello World"

我很困惑为什么会收到此错误,因为根据我的理解,如果 app 在init文件中声明,我应该能够导入它。

标签: pythonpython-3.xdebuggingflaskpython-import

解决方案


This is happening because site is a module within the Python standard library (https://docs.python.org/3/library/site.html). Your module name is clashing with it and the interpreter is loading from the library first, hence not finding the app variable. There are a few ways around this but I suspect you're not very attached to the name so I'd just change it. If you rename your site folder to web (or any other name not used by the Python std library), it'll work.


推荐阅读