[英]Python ImportError: attempted relative import with no known parent package
I'm learning fastapi .我正在学习fastapi 。 I have a very simple project structure like this
我有一个非常简单的项目结构,像这样
.
├── __init__.py
├── database.py
├── main.py
├── models.py
├── requirements.txt
└── schemas.py
Inside main.py
is里面
main.py
是
from fastapi import FastAPI
from typing import Optional
from . import schemas, models
from .database import engine
app = FastAPI()
# more code here...
but when I run this with uvicorn main:app --reload
I get the error但是当我用
uvicorn main:app --reload
运行它时,我得到了错误
...
...
from .从 。 import schemas, models
导入模式、模型
ImportError: attempted relative import with no known parent packageImportError:尝试在没有已知父包的情况下进行相对导入
I don't understand why I'm getting this error.我不明白为什么我会收到这个错误。 I'm loosely following this tutorial .
我正在松散地遵循本教程。 I've also read through numerous related SO questions ( 1 2 3 ), but none seem to match my situation.
我还阅读了许多相关的 SO 问题( 1 2 3 ),但似乎没有一个符合我的情况。
不要将文件导入为“from . import schemas, models”,而是尝试像这样直接导入它 - import schemas,models 。我认为这可能会奏效。
Although your logic of "."虽然你的逻辑“。” directory is right, relative imports always relay on environment configurations, which may vary depending by IDE, venv and such stuffs, EG the
env
may vary at runtime in VScode based on the launch.json
and settings.json
目录是正确的,相对导入总是依赖于环境配置,这可能会因 IDE、venv 等而有所不同,例如,在 VScode 中,
env
可能会根据launch.json
和settings.json
在运行时有所不同
I'd suggest you to better structure your project so that it contains package folders containing the __init__.py
and the homonym module name, thus you can setup the import behave in the __init__.py
file.我建议您更好地构建您的项目,使其包含包含
__init__.py
和同音模块名称的包文件夹,因此您可以在__init__.py
文件中设置导入行为。
Exempli Gratia: Here Database
, Model1
and Model2
are classes in the database/database.py
and models/models.py
示例感谢:这里
Database
, Model1
和Model2
是database/database.py
和models/models.py
中的类
Where database/__init__.py
is defined as follows to link the Database class inside database.py the import at the "upper" folder其中
database/__init__.py
定义如下,以链接 database.py 中的 Database 类,在“上层”文件夹中导入
And the models/__init__py
similarly links models.py
classes to the "upper" folder并且
models/__init__py
类似地将models.py
类链接到“上层”文件夹
from
keyword uses the __init__.py
inside the called directory by default to import objects to main, thus you could define specific instances or variables along with constants directly into the __init__.py
at will along with any kind of operation (although is not always a good thing to do...)from
关键字引用目录时,默认情况下使用被调用目录中的__init__.py
将对象导入 main,因此您可以随意将特定实例或变量与常量一起定义到__init__.py
中,以及任何类型的操作(虽然并不总是一件好事......)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.