简体   繁体   中英

Cloud Run Python - Unable to import

I'm able to build and deploy a super simple python app, based on FastApi, to Cloud Run. However I now need to expand the app somewhat and need to organise my functions into modules which I would have expected to be very trivial to import and reference from my main.py

I have my project structured thus:

app <dir>
|
|-- alpha <dir>
|    |
|    |-- beta.py
|    |-- __init__.py
|
|-- main.py

In main.py I'm adding:

from alpha import beta

Then running main.py locally everything is fine, I can call functions in beta.py with:

beta.dostuff()

However when I try to deploy this to Cloud Run, the deployment fails with:-

line 2, in <module> from alpha import beta ModuleNotFoundError: No module named 'alpha'

This made me think that perhaps my Dockerfile wasn't copying the alpha directory properly, but my Dockerfile is very simple as it is just:

FROM python:3.9

COPY . ./

RUN python -m pip install --upgrade pip &&\
    pip install -r requirements.txt

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080"]

So that is copying everything (that isn't in my .dockerignore).

When I delete the /app/alpha directory completely, remove the import and stub out the calls to functions in beta.py so that everything is running out of main.py the application deploys and runs just fine again.

I must be missing something really dumb. Can anyone see what I might be missing? Would be very grateful for any pointers.

The problem is not in Cloud Run but in the way uvicorn runs the application. You would need to change the import statement so that it refers from the base path. Change your import statement to the following:

from app.alpha import beta

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM