错误:加载 ASGI 应用程序时出错。导入字符串“main”必须采用“<module>:<attribute>”格式

问题描述 投票:0回答:2

尝试使用 uvicorn 测试我的第一个 FastAPI 应用程序。

以下代码是在Jupyter Notebook上编写的,并在目录中保存为

'main.py'
/home/user

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

从我正在运行的同一目录:

$uvicorn main --reload

它抛出以下错误:

错误:加载 ASGI 应用程序时出错。导入字符串“main”必须位于 格式“:”。

fastapi uvicorn asgi
2个回答
7
投票

如错误所示,“字符串

main
必须采用格式
"<module>:<attribute>"
”。因此,您应该使用:

uvicorn main:app --reload

我强烈建议您看一下 FastAPI 教程

命令 uvicorn

main:app
指的是:

  • main
    :文件
    main.py
    (Python
    "module"
    )。
  • app
    :在
    main.py
    内部使用线
    app = FastAPI()
    创建的对象。
  • --reload
    :代码更改后重新启动服务器。 仅用于开发

2
投票

完全相同的错误消息,但场景不同

import uvicorn
from fastapi import FastAPI
  
    
app = FastAPI()
    
    
@app.get('/')
def index():
    return {'Message': 'This is only a message!'}
    
    
if __name__ == '__main__':
    uvicorn.run('main:app', port=8000, reload=True)

此消息可能是由于对方法 run 的调用而出现的,该方法不接受位置参数或关键字参数作为变量。而是作为纯文本。就像上面的例子一样。

© www.soinside.com 2019 - 2024. All rights reserved.