fastapi简介

一种基于python的后端网络框架

各种参数

路径参数

当我们使用路径参数时一般要导入Path

1
from fastapi import Path 

用法则是

1
2
3
@app.get("/路径名/{id}")
async def get_id(id : int = Path(...,gt=0,lt=100)):
return {"id":id,"msg": f"this is the {id}"}

如上,对参数进行限制

查询参数

当声明的参数不是路径参数时,路径操作函数会将其自动定义为查询参数

当我们使用路径参数时一般要导入Query,和路径参数相同,用法和路径参数相同

请求体参数

作用:创建、更新资源

在http协议中,一个完整的请求由三部分组成:

请求行:包含方法、URL、协议版本

请求头:元数据信息

请求体:实际要发送的数据内容

1
2
3
4
5
6
7
8
from pydantic import BaseModel
class User{BashModel}:
username:str
password:str

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

外部函数进行类型注解:Field,Field用法和Path和Query一样

1
2
3
4
5
from pydantic import Field

class User(BaseModel):
username : str =Field(default="田鼠浩二",min_length=4,max_length=10,description="此处为注释")
password : str =Field()

响应类型

默认情况下,fastapi会自动将路径操作函数返回的python对象转为json格式,并包装为jsonResponse返回

相应类型设置方式,装饰器中指定响应类,场景:固定返回类型(HTML、纯文本)

返回响应对象,场景:文件下载、图片、流式响应

响应html格式

设置相应类为htmlResponse,当前接口返回HTML内容

1
2
3
4
5
6
from fastapi.responses import HTMLResponse

@app.get("/html",response_class=HTMLResponse)
async def get_html():
return "<h1>hello</h1>"
#返回的body是html类型

响应文件格式

FileResponse高效返回文件内容(图片,视频,MP3等)

1
2
3
4
5
6
from fastapi.responses import FileResponse

@app.get("/file")
async def get_file():
path="" #本地文件路径
return FileResponse(path)

自定义响应数据格式

response_model 是路径操作装饰器的关键参数,通过一个pydantic模型严格定义和约束api端点的输出格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from pydantic import BaseModel

class News(BaseModel):
id:int
title:str
content:str

@app.get("/news/{id}",response_model=News)
async def get_news(id:int):
return {
"id":id,
"title":title
"content":content
}

异常处理

客户端引发的错误,使用fastapi.HTTPException来中断正常的处理流程,并返回标准错误响应

1
2
3
4
5
6
7
8
9
from fastapi import HTTPException

@app.get("/news/{id}")

async def get_news(id:int):
id_list={1,2,3,4,5,6}
if id not in id_list:
raise HTTPException(status_code=404,detail="你查找的news不存在")
return {"id":id}