tiangolo / uvicorn-gunicorn-fastapi-docker

Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python with performance auto-tuning.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to manage imports

mroelandts opened this issue · comments

Current file structure for my project is:

.
├── app
│   ├── crud.py
│   ├── database.py
│   ├── __init__.py
│   ├── main.py
│   ├── models.py
│   └── schemas.py
├── Dockerfile
└── requirements.txt

I have imports in my main.py like:

from . import crud, models, schemas

But when I run the docker I get ImportError: attempted relative import with no known parent package

What is the expected import methode for running inside the docker container?
I can do a

import sys
sys.path.insert(0, '/')

from app import crud, models, schemas

inside of the main.py but, this is the only solution? Am I missing something obvious?

Try import crud, models, schemas

@ClimenteA anwser is an valid option.
But I like to have the from app import crud format for self made code.
I noticed that in the docker container the pythonpath was already /app.
So this means that it is better to edit the Dockerfile to contain

COPY ./app /app/app

so that your main file ends up on /app/app/main.py

Maybe the README.md needs to be edited to contains this line as default instead of COPY ./app /app.

commented

@mroelandts

I have tried:

COPY ./app /app/app

But I can't still do from app.something import test.py without the: sys.path.insert(0, '/')

Thanks for the help here @ClimenteA ! 👏 🙇

Thanks for reporting back and closing the issue @mroelandts 👍

@psdon if you still have problems please create a new issue following the template.

Sorry for the long delay! 🙈 I wanted to personally address each issue/PR and they piled up through time, but now I'm checking each one in order.