FastAPI throws an error (Error loading ASGI app. Could not import module “api”)

不想你离开。 提交于 2020-08-07 06:46:20

问题


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

I run this command,

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


回答1:


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

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

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

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.



回答2:


its typo in "api" check your file name.




回答3:


I had the same problem and i am solved it adding package name before main, in your case try with

uvicorn src.main:app --reload



来源:https://stackoverflow.com/questions/60819376/fastapi-throws-an-error-error-loading-asgi-app-could-not-import-module-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!