FastAPI 启动指南:详细步骤与示例
要启动 FastAPI 应用程序,可以按照以下步骤进行操作:
- **确保已经安装了 FastAPI 和 uvicorn。**可以使用以下命令安装它们:
pip install fastapi
pip install uvicorn
- 创建一个 Python 文件,例如 'main.py',并导入 FastAPI 和其它需要的模块:
from fastapi import FastAPI
- 创建一个 FastAPI 应用程序实例:
app = FastAPI()
- 定义一个路由和对应的处理函数,例如:
@app.get('/')
def read_root():
return {'Hello': 'World'}
- **最后,使用 uvicorn 命令启动应用程序。**在命令行中运行以下命令:
uvicorn main:app --reload
这将启动 uvicorn 服务器,并将应用程序运行在默认的 'http://localhost:8000' 地址上。你可以在浏览器中访问该地址来查看应用程序的输出。
注意: 'main:app' 中的 'main' 指的是你的 Python 文件名(不包括 '.py' 扩展名),'app' 是你创建的 FastAPI 应用程序实例的变量名。
原文地址: https://www.cveoy.top/t/topic/cgUd 著作权归作者所有。请勿转载和采集!