环境说明
Python版本:python3.12
虚拟环境:venv
创建虚拟环境
执行命令:
python -m venv venv
激活虚拟环境:
venv\Scripts\activate
安装依赖
安装FastAPI:
pip install fastapi
安装uvicorn:
pip install uvicorn['standard']
生成依赖清单:
pip freeze > requirements.txt
编写第一个FastAPI程序
main.py
from fastapi import FastAPI
# 创建应用
app = FastAPI()
# 定义接口
@app.get("/")
async def hello():
return {"msg": "你好,张大鹏!"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8888)
启动服务
直接启动:
python main.py
使用命令启动:
uvicorn main:app --host 0.0.0.0 --port 8888
访问接口
浏览器访问:
http://localhost:8888/
http://localhost:8888/docs