英文:
Absolute imports works either in tests or in uvicorn
问题
以下是要翻译的部分:
我有一个有点奇怪的问题,即我有这个结构:
|-tests
| |-__init__.py
| |-domain
| | |-items
| | | |-test_service.py
| |-test_app.py
|-poetry_demo
| |-__init__.py
| |-app.py
| |-domain
| | |-__init__.py
| | |-items
| | | |-service.py
| | | |-controller.py
| | | |-__init__.py
| | | |-model.py
在app.py
中,我执行以下操作:
from fastapi import FastAPI
from poetry_demo.domain.items.controller import ItemsController
from poetry_demo.domain.items.service import ItemsService
app = FastAPI()
app.include_router(ItemsController(service=ItemsService).router, prefix="/items")
当我进入poetry_demo
目录并使用uvicorn app:app --reload
运行uvicorn时,我收到以下错误消息:
from poetry_demo.domain.items.controller import ItemsController
ModuleNotFoundError: No module named 'poetry_demo'
但与此同时,当我从主目录(在poetry_demo
上面一级)运行pytest
时,它完全正常工作。
为了使应用程序正常运行,我需要将app.py
中的导入更改为:
from domain.items.controller import ItemsController
from domain.items.service import ItemsService
然后它可以正常工作,但是... 测试出现了问题。
我尝试将导入更改为相对导入(.domain...
),但然后我收到以下错误:
from .domain.items.controller import ItemsController
ImportError: attempted relative import with no known parent package
希望能有所帮助
英文:
I have a bit of an odd problem, namely I have this structure:
|-tests
| |-__init__.py
| |-domain
| | |-items
| | | |-test_service.py
| |-test_app.py
|-poetry_demo
| |-__init__.py
| |-app.py
| |-domain
| | |-__init__.py
| | |-items
| | | |-service.py
| | | |-controller.py
| | | |-__init__.py
| | | |-model.py
And in app.py
I do
from fastapi import FastAPI
from poetry_demo.domain.items.controller import ItemsController
from poetry_demo.domain.items.service import ItemsService
app = FastAPI()
app.include_router(ItemsController(service=ItemsService).router, prefix="/items")
And when I go into poetry_demo
dir and run uvicorn with uvicorn app:app --reload
, I am getting an error:
from poetry_demo.domain.items.controller import ItemsController
ModuleNotFoundError: No module named 'poetry_demo'
But on the same time, when I run pytest
from the main directory (one above poetry_demo
), it works perfectly.
To have app running, I need to change app.py
imports to:
from domain.items.controller import ItemsController
from domain.items.service import ItemsService
And then it works, but... tests are breaking.
I tried changing import to relative (.domain...
), but then I am getting
from .domain.items.controller import ItemsController
ImportError: attempted relative import with no known parent package
Any help is appreciated
答案1
得分: 0
我已解决了这个问题。从顶级目录运行 everything 有所帮助。
而不是
uvicorn app:app --reload
我执行
uvicorn poetry-demo.app:app --reload
我还可以从那里运行测试(或从IDE运行,也能完美运行)。
也许这会对某人有所帮助
英文:
Okay, so I've solved the problem. Running everything from the top directory helped.
Instead of
uvicorn app:app --reload
I do
uvicorn poetry-demo.app:app --reload
I also run tests from there (or from IDE, it also works perfectly).
Maybe this'll help someone
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论