[英]Import Error of Flask Application in IDLE console
I want to import a Flask object into IDLE so that I can experiment and explore.我想将一个 Flask object 导入 IDLE 以便进行实验和探索。
I am able to launch an interactive command line session successfully by typing python
from the project directory.我可以通过从项目目录中键入
python
成功启动交互式命令行 session。
Python 3.7.5 (default, Nov 18 2019, 00:27:11)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from app import app
>>> dir(app)
['Flask', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'app', 'create_app', 'current_app', 'index', 'make_response', 'randint']
>>> exit()
But I want to use IDLE for this exploration.但我想使用 IDLE 进行这种探索。
So I added my project path to sys.path
in IDLE.所以我将我的项目路径添加到 IDLE 中的
sys.path
中。 When I try to import using from app import app
, I get the error AttributeError: module 'config' has no attribute 'settings
.当我尝试使用
from app import app
时,出现错误AttributeError: module 'config' has no attribute 'settings
。
The code sample:代码示例:
from flask import Flask
def create_app():
app = Flask(__name__,instance_relative_config=True)
app.config.from_object('config.settings')
app.config.from_pyfile('settings.py',silent=True)
return app
Project structure:项目结构:
project_dir/
├── app/
│ ├── app.py
├── config/
│ │
│ └── settings.py
└── instance/
└── settings.py
Why is IDLE unable to find the settings.py
module in the config
directory?为什么 IDLE 在
config
目录下找不到settings.py
模块?
NOTE: When I remove the line app.config.from_object('config.settings')
, the import succeeds.注意:当我删除行
app.config.from_object('config.settings')
时,导入成功。
IDLE only finds files when you use the IDLE open command to edit a file. IDLE 仅在您使用 IDLE open 命令编辑文件时查找文件。 When you ask IDLE to execute your code, it calls compile() and passes the result to the executing python.
当您要求 IDLE 执行您的代码时,它会调用 compile() 并将结果传递给正在执行的 python。
app.config.from_object('config.settings')
fails for the reason given in the error message: the config
object has no attribute settings
. app.config.from_object('config.settings')
由于错误消息中给出的原因而失败: config
object has no attribute settings
。 Adding import config.settings
may fix this.添加
import config.settings
可能会解决此问题。 I cannot be sure because your project structure diagram is ambiguous.我无法确定,因为您的项目结构图不明确。 It shows
config
as both a top-level directory, parallel to app
and instance
and as a subdirectory of app
.它将
config
显示为与app
和instance
平行的顶级目录以及app
的子目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.