简体   繁体   English

Cloud Run Python - 无法导入

[英]Cloud Run Python - Unable to import

I'm able to build and deploy a super simple python app, based on FastApi, to Cloud Run.我能够构建一个基于 FastApi 的超级简单的 python 应用程序并将其部署到 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但是,我现在需要稍微扩展应用程序,并且需要将我的功能组织到模块中,我希望从我的 main.py 导入和引用这些模块非常简单

I have my project structured thus:我的项目结构如下:

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

In main.py I'm adding:在 main.py 我添加:

from alpha import beta

Then running main.py locally everything is fine, I can call functions in beta.py with:然后在本地运行 main.py 一切都很好,我可以调用 beta.py 中的函数:

beta.dostuff()

However when I try to deploy this to Cloud Run, the deployment fails with:-但是,当我尝试将其部署到 Cloud Run 时,部署失败并显示:-

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:这让我觉得也许我的 Dockerfile 没有正确复制 alpha 目录,但我的 Dockerfile 非常简单,因为它只是:

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).这就是复制所有内容(不在我的 .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.当我完全删除 /app/alpha 目录时,删除导入并存根对 beta.py 中函数的调用,以便一切都用完 main.py 应用程序部署并再次运行良好。

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.问题不在于Cloud Run ,而在于uvicorn运行应用程序的方式。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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