# 创建fastapi对象
from fastapi import FastAPI, Form
from pydantic import BaseModel
# 创建一个FastAPI实例
app = FastAPI()
#写自己的接口
# 表单数据
@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
print(f"用户名为:{username}")
print(f"密码为:{password}")
return {"username": username}
@app.post("/receive_raw_json/")
async def receive_raw_json(data: dict):
print(f"接收到的数据为:{data}")
return {"received_data": data}
# 通过Pydantic方式进行传参
class Item(BaseModel):
name: str
description: str
price:float
# 接收JSON数据的POST接口
@app.post("/items/")
async def create_item(item: Item):
# 可以直接使用item对象,FastAPI会自动解析JSON
print(item.model_dump())
return {"item": item.model_dump(), "message": "Item created successfully"}
# 把fastapi对象监听在某个端口上
if __name__ == "__main__":
import uvicorn
#3.利用uviconrn将fastapi对象拉起来
uvicorn.run(app, host="0.0.0.0", port=8000)