python - 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文件中声明,我应该能够导入它。
解决方案
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.
推荐阅读
- amazon-web-services - 尝试在 aws amplify 上添加站点地图
- python - Altair:创建一个带有类似于 mark_errorband 的 max-min 波段的 mark_line 图
- swift - 使 NSPanel 始终位于顶部
- java - 在多线程计数器Java中实现同步
- c++ - 用迷宫求解程序回溯逻辑错误
- python - 如何通过将源代码保存在 Github 中,将我的 python 程序作为 Web 应用程序在线共享?
- c++ - 如何修复这个未声明的标识符?(C++)
- javascript - ReactTable 上页面大小的自定义下拉菜单
- django - 表单集未在 Django 3 中显示
- node.js - 如何使用 GSuite 帐户通过 node.js 发送邮件?