Uvicorn: 模块 “app.app” 中未找到属性 “app”

huangapple go评论104阅读模式
英文:

Uvicorn: Attribute "app" not found in module "app.app"

问题

main.py

import uvicorn

if __name__ == "__main__":
    uvicorn.run("app.app:app", port=8000, reload=True)

app.py

from fastapi import FastAPI
app = FastAPI()

@app.get("/", tags=['ROOT'])
async def root() -> dict:
    return {"Ping": "Pong"}

运行 main.py 会导致以下错误:

加载 ASGI 应用程序时出错。在模块 "app.app" 中找不到属性 "app"。

我尝试将 app.py 文件重命名,并直接从命令行使用 uvicorn 启动,但仍然遇到相同的错误。

英文:

I'm trying to follow a basic guide to begin using FastAPI and uvicorn. I followed steps in the video, and wrote the same code(And file structure is the same, app.py in app folder, main.py in outer folder)

main.py

import uvicorn

if __name__ == "__main__":
    uvicorn.run("app.app:app", port=8000, reload=True)

app.py

from fastapi import FastAPI
app = FastAPI()

@app.get("/", tags=['ROOT'])
async def root() -> dict:
    return{"Ping":"Pong"}

Launching main.py results in the following error:

Error loading ASGI app. Attribute "app" not found in module "app.app".

I've tried renaming app.py file and launching it directly from command line using uvicorn but got the same error.

答案1

得分: 1

你应该使用 app:app 启动 uvicorn。文件名已经在 app:app 的第一部分中声明。

import uvicorn

if __name__ == "__main__":
    uvicorn.run("app:app", port=8000, reload=True)

此外,你也可以在终端中这样运行 uvicorn

uvicorn app:app --port 8000 --reload
英文:

You should start uvicorn with app:app. The file name is already declared in the first part of app:app.

import uvicorn

if __name__ == "__main__":
    uvicorn.run("app:app", port=8000, reload=True)

Also, you could run uvicorn from your terminal like so:

uvicorn app:app --port 8000 --reload

huangapple
  • 本文由 发表于 2023年8月5日 15:34:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76840592.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定