fastapi速成2

路径参数与查询参数:

python 复制代码
from fastapi import FastAPI,Path

import uvicorn

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World1"}
# 路径参数演示:
@app.get("/items/{item_id}")
async def read_item(item_id: int = Path(..., gt=0,lt=99,description="范围0-99")):
    return {"item_id": item_id, "message": f"这是 {item_id}"}

@app.get("/xmbl/{name}")
async def get_name(name: str=Path(...,min_length=1,max_length=10)):
    return {"msg":f"my name is {name}"}

#查询参数演示:
@app.get("/aaa/bbb")
async def get_name(skip: int,limit: int = 10):
    return {"skip":skip,"limit":limit}
if __name__ == "__main__":
    # 启动uvicorn服务器,绑定127.0.0.1:8000
    uvicorn.run("test5:app", host="127.0.0.1", port=8000)

Field注释:

python 复制代码
class Token(BaseModel):
    access_token: str = Field(..., description="access token", min_length=1, max_length=20)
    token_type: str
    expires_in: int = Field(..., description="expires time")


@app.post("/test")
async def test(token: Token):
    return token

HTML格式:

python 复制代码
@app.get("/hello", response_class=HTMLResponse)
async def hello_world():
    return "<h1>Hello World</h1>"

文件格式:

python 复制代码
@app.get("/get_file")
async def get_file():
    return FileResponse("./files/an.png")

自定义响应类型:

python 复制代码
class XMBL(BaseModel):
    id: int
    name: str
    type: str


@app.get("/xmbl/{id}", response_model=XMBL)
async def get_xmbl(id: int):
    return {
        "id": id,
        "name": f"第{id}小马的名字",
        "type": "类型"
    }

异常:

python 复制代码
@app.get('/xmbl2/{id}')
async def get_xmbl2(id: int):
    is_list = [1,2,3,4,5,6,7]
    if id not in is_list:
        raise HTTPException(status_code=404,detail="当前id不存在")
    return {
        "id": id
    }

总项目(fastapi项目,创建需要激活,也可以看前一篇文章,是手工创建项目的写法):

main.py

python 复制代码
from fastapi import FastAPI,HTTPException
from pydantic import BaseModel, Field
from fastapi.responses import HTMLResponse, FileResponse

app = FastAPI()


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


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello123 {name}"}


class User(BaseModel):
    username: str
    password: str


@app.post("/register")
async def register(user: User):
    return user


class Token(BaseModel):
    access_token: str = Field(..., description="access token", min_length=1, max_length=20)
    token_type: str
    expires_in: int = Field(..., description="expires time")


@app.post("/test")
async def test(token: Token):
    return token


@app.get("/hello", response_class=HTMLResponse)
async def hello_world():
    return "<h1>Hello World</h1>"


@app.get("/get_file")
async def get_file():
    return FileResponse("./files/an.png")


class XMBL(BaseModel):
    id: int
    name: str
    type: str


@app.get("/xmbl/{id}", response_model=XMBL)
async def get_xmbl(id: int):
    return {
        "id": id,
        "name": f"第{id}小马的名字",
        "type": "类型"
    }

@app.get('/xmbl2/{id}')
async def get_xmbl2(id: int):
    is_list = [1,2,3,4,5,6,7]
    if id not in is_list:
        raise HTTPException(status_code=404,detail="当前id不存在")
    return {
        "id": id
    }

test_main.http

python 复制代码
# Test your FastAPI endpoints

GET http://127.0.0.1:8000/
Accept: application/json

###

GET http://127.0.0.1:8000/hello/User
Accept: application/json

###

依赖注入:

创建依赖项

导入depends

声明依赖项

python 复制代码
from fastapi import FastAPI,Query,Depends

import uvicorn

app = FastAPI()

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


async def common_parameters(
        skip: int = Query(0,ge=0),
        limit: int = Query(10,le=10),
):
    return {"skip": skip, "limit": limit}


@app.get("/ziyue/test")
async def get_ziyue_test(commons=Depends(common_parameters)):
    return commons

@app.get("/rourou/test")
async def get_rourou_test(commons=Depends(common_parameters)):
    return commons

if __name__ == "__main__":
    # 启动uvicorn服务器,绑定127.0.0.1:8000
    uvicorn.run("test8:app", host="127.0.0.1", port=8000)

ORM(对象关系映射):

pip install sqlalchemyasyncio aiomysql -i https://pypi.tuna.tsinghua.edu.cn/simple/

相关推荐
鲨鱼辣钊2 小时前
【FastAPI筑基-Day19】APScheduler定时任务全实战|自动执行、动态启停、后台常驻
java·spring·fastapi
傲笑风7 小时前
【openvino】tinybert基于openvino服务化部署(四)
人工智能·python·自然语言处理·nlp·bert·openvino
维基框架8 小时前
WIKI 知识库 v1.1.1 正式发布
人工智能·python
峰向AI11 小时前
GenOffice:开源 Office 套件,字节级保留、本地转换、BYOK模式
github
谢白羽12 小时前
SGLang的AWQ量化笔记
笔记·python·sglang
迷迭香yy12 小时前
基金档案数据工程实战从收入分析到持仓穿透的Python解析 IG50免费开源股票数据API接口
开发语言·python
其实防守也摸鱼12 小时前
权限提升与横向移动:从内网渗透到域控的完整技术图谱
运维·服务器·数据库·安全·github·copilot·渗透
清水白石00812 小时前
Python 类型设计深度解析:TypedDict 能否替代 dataclass?从 JSON 数据边界到 API 设计的最佳实践
java·python·json
m4Rk_13 小时前
【论文阅读】Agent 记忆机制(57):MemSearch-o1——从查询词元生长证据,重组 Deep Search 记忆路径
论文阅读·人工智能·学习·开源·github
️学习的小王13 小时前
Git项目提交忽略文件怎么做?以Python项目为例,详解.gitignore
git·python·elasticsearch