FastAPI引发错误(加载ASGI应用时出错.无法导入模块"api") [英] FastAPI throws an error (Error loading ASGI app. Could not import module "api")

查看:2081
本文介绍了FastAPI引发错误(加载ASGI应用时出错.无法导入模块"api")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用uvicorn网络服务器运行FastAPI,但是会引发错误.

I tried to run FastAPI using uvicorn webserver but it throws an error.

我运行此命令,

uvicorn api:app --reload --host 0.0.0.0

但是终端中有一个错误.

but there is an error in the terminal.

Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
Started reloader process [23445]
Error loading ASGI app. Could not import module "api".
Stopping reloader process [23445]

我非常感谢任何建议或建议

I really appreciate any recommendations or suggestions

推荐答案

之所以会发生这种情况,是因为您与FastAPI应用程序实例不在同一个文件夹中

It's happens because you are not in the same folder with your FastAPI app instance more spesifcally:

假设我有一个这样的应用程序树;

Let's say i have a app-tree like this;

my_fastapi_app/
├── app.yaml
├── docker-compose.yml
├── src
│   └── main.py
└── tests
    ├── test_xx.py
    └── test_yy.py

$ pwd         # Present Working Directory
/home/yagiz/Desktop/my_fastapi_app

所以我不在与我的应用程序实例相同的文件夹中,因此,如果我尝试使用uvicorn运行我的应用程序,则会收到类似您的错误信息

So i'm not inside the same folder with my app instance, so if i try to run my app with uvicorn i'll get an error like yours

$ uvicorn main:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [40645] using statreload
ERROR:    Error loading ASGI app. Could not import module "main".

答案非常简单,您只需要更改工作目录

The answer is so simple you just need to change your working directory

cd src

现在我和我的应用程序实例在文件夹中

Now i'm inside of the folder with my app instance

src
└── main.py

再次运行您的uvicorn

Run your uvicorn again

$ uvicorn main:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [40726] using statreload
INFO:     Started server process [40728]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

这篇关于FastAPI引发错误(加载ASGI应用时出错.无法导入模块"api")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆