前篇学习了关于请求参数相关的约束验证, Request

包括 路径参数 , 查询参数, 枚举参数, 文件参数, 类型验证, 多参数嵌套验证, 请求体嵌套验证, Cookie 和 Header 等, 了解完这些对于接口的请求基本就到位了.

这篇便主要针对响应处理进行介绍 Response

项目结构

主要来自慕课网的学习公开课笔记, 目录结构如下:

base

  • __ init __.py
  • base_01.py
  • base_02.py
  • base_03.py
  • base_04.py
  • ...

main.py

其中 main.py 的内容如下:

from fastapi import FastAPI
import uvicorn from base import app01
from base import app02
from base import app03
from base import app04 app = FastAPI(
title="FastAPI 基础教程",
version='1.0.0',
docs_url='/docs'
) app.include_router(app01, prefix='/app01', tags=['请求参数和验证'])
app.include_router(app02, prefix='/app02', tags=['响应处理和配置'])
app.include_router(app03, prefix='/app03', tags=['依赖注入和系统'])
app.include_router(app04, prefix='/app04', tags=['安全认证和授权']) if __name__ == '__main__':
uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True, workers=1)

响应体处理 Response

对应的资源引入, 主要是表达, 文件上传, 异常类, 模型类, 类型校验等如下:

# app02.py

from fastapi import APIRouter, status, Form, File, UploadFile, HTTPException
from typing import Optional, List, Union
from pydantic import BaseModel, EmailStr app02 = APIRouter()

响应模型类 response_model

演示用一个常用的用户信息类, 包含用户的姓名, 昵称, 电话, 邮箱, 地址等

# 用户信息基类 (共有)
class User(BaseModel):
username: str
email: EmailStr # pip install pydantic[email]
mobile: str = '10086' # 真实项目中, 可用 Field 做正则校验
full_name: Optional[str] = None
address: str = None # 用户信息输入类, 会多输入一个密码
class UserIn(User):
password: str # 用户信息输出类, 不返回密码, 其他都返回
class UserOut(User):
pass # 用户数据模拟
users = {
"user01": { 'username': 'cj', 'password': 123123, 'email': 'user01@example.com' },
"user02": { 'username': 'youge', 'password': 123456, 'email': 'user02@example.com' }
}

请求用户信息响应, 前端输入是一个post请求 UerIn, 响应的模型是 UserOut .

@app02.post('/response_model', response_model=UserOut, response_model_exclude_unset=True)
async def response_model(user: UserIn):
"""response_model_exclude_unset=True 表示不用默认值, 前端传啥用啥""" print(user.password, "密码不会被返回的")
return users['user01']

响应属性:

@app02.post('/response_model/attributes',
# response_model=UserOut
# response_model=Union[UserIn, UserOut]
response_model=List[UserOut]
# response_model_include=['username', 'email'],
# response_model_exclude=['mobile']
)

可以进行合并, 选择等灵活操作. 比如我们要返回 UserIn 和 UserOut 但密码不返回, 也是可以取巧处理的.

async def response_model_attributes(user: UserIn):
# Union[UserIn, UserOut] 后, 删掉 password 也能返回成功的
del user.password
return [user, user]

响应状态码 status

查看它的源码其实就是对类似 200, 404, 500 等响应码进行语义化而已, 其实也多此一举我觉得.

@app02.post('/status_code', status_code=200)
async def status_code():
return { 'status_code': 200 } @app02.post('/status_attribute', status_code=status.HTTP_200_OK)
async def status_attribute():
print(type(status.HTTP_200_OK))
return { 'status_code': status.HTTP_200_OK }

这里的 status.HTTP_200_OK, 其实就是数字 200.

表单数据处理 Form

请求和响应都经常会用到, 最多的就是注册, 登录相关,

注意这里用 Form 类则需要 pip install python-multipart

@app02.post('/login')
async def login(username: str = Form(...), password: str = Form(..., regex='^a')): # Form 类的校验方法类似 Path, Query, Cookie, Header 等 # 走完认证逻辑后, 返回用户名
return { 'username': username }
curl -X 'POST' \
'http://127.0.0.1:8000/app02/login' \
-H 'accept: application/json' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'username=admin&password=admin'

单/多/大文件上传处理 File, UploadFile

@app02.post('/file')
async def file(file: bytes = File(...)):
# async def file(file: List[bytes] = File(...)):
"""使用 File 类, 文件内容会议 bytes 形式读入内存, 适合小文件上传"""
return { 'file_size': len(file) } @app02.post('/upload_files')
async def upload_files(files: List[UploadFile] = File(...)):
"""
使用 UploadFile 类的优势:
1. 文件优先存在内存, 如果达到阈值后, 将被保存在磁盘中
2. 适合于图片, 视频等大文件
3. 可以获取上传文件的元数据, 如文件名, 创建时间等
4. 有文件对象的异步接口
5. 上传的文件是 Pyhon 文件对象, 可以使用 write(), read(), seek(), close() 等操作 """
for file in files:
contents = await file.read()
print('文件的内容是: ', contents) return { 'filename': files[0].filename, 'content_type': files[0].content_type }

接口文档配置

@app02.post(
'/path_operation_configuration',
response_model=UserOut,
# tags=["Path", "Operation", "Configuration"],
summary="This is summary",
description="这是一个描述哈",
response_description="给前端响应一个描述",
deprecated=True,
status_code=status.HTTP_200_OK
)
async def path_operation_configuration(user: UserIn):
"""
路径操作配置
请求: 用户信息
响应: 返回结果 """
return user

应用文档配置

# main.py 

app = FastAPI(
title="FastAPI 基础教程",
version='1.0.0',
docs_url='/docs'
)

异常类处理 HTTPException

这些都是很常见的操作了, 简单粗暴.

@app02.get('/http_exception')
async def http_exception(city: str):
if city != 'Beijing':
raise HTTPException(status_code=404, headers={ "X-Error": "Error" }, detail="City not found")
return { 'city': city }

这样关于响应模块的也就基本差不多了, 当然在实际应用中, 响应要怎么弄其实都看自己灵活配置, 重点还是请求校验这块更为关键哦.

FastAPI-响应处理和配置的更多相关文章

  1. fastapi四:uvicorn.run支持的参数

    `app:指定应用app,'脚本名:FastAPI实例对象'.FastAPI实例对象 host: 字符串,允许被访问的形式 locahost.127.0.0.1.当前IP.0.0.0.0,默认为127 ...

  2. nginx应用总结(1)--基础认识和应用配置

    在linux系统下使用nginx作为web应用服务,用来提升网站访问速度的经验已五年多了,今天在此对nginx的使用做一简单总结. 一.nginx服务简介Nginx是一个高性能的HTTP和反向代理服务 ...

  3. STM32F0xx_RTC实时时钟配置详细过程

    Ⅰ.概述 今天总结RTC(Real Time Clock)实时时钟相关的知识,顺带将BKP简单总结一下. STM32的RTC模块和时钟配置系统(RCC_BDCR寄存器)处于后备区域,即在系统复位或从待 ...

  4. modsecurity配置指令学习

    事务(transactions) Console(控制台) 1 Introduction Modsecurity是保护网络应用安全的工作.不,从零开始.我常称modsecurity为WAF(网络应用防 ...

  5. LVS 介绍以及配置应用

    1.负载均衡集群介绍 1.1.什么是负载均衡集群 负载均衡集群提供了一种廉价.有效.透明的方法,来扩展网络设备和服务器的负载.带宽.增加吞吐量.加强网络数据的处理能力.提高网络的灵活性和可用性 搭建负 ...

  6. 为 IIS 7.0 配置 <system.webServer>

    Web.config 文件中的 system.webServer 节用于指定适用于 Web 应用程序的 IIS 7.0 设置.system.WebServer 是 configuration 节的子级 ...

  7. centOS7配置DNS服务器

    世上无难事只怕有心人,遇事千万千万不要抵触,消极的情绪是失败之母,一点一滴,踏踏实实是通往幸福的捷径. 历经激动,受挫,抵触和鼓励以及征服,终于配好了让我欢喜让我忧的dns.在这里记录下来,希望能够给 ...

  8. JMeter 检查点之响应断言(Response Assertion)

    检查点之响应断言(Response Assertion)   by:授客 QQ:1033553122 JMeter断言用于对sampler(采样器)进行额外检查,且在相同作用域中,每执行完一个samp ...

  9. nginx应用总结(1)-- 基础知识和应用配置梳理

    在linux系统下使用nginx作为web应用服务,用来提升网站访问速度的经验已五年多了,今天在此对nginx的使用做一简单总结. 一.nginx服务简介Nginx是一个高性能的HTTP和反向代理服务 ...

  10. 如何:为 IIS 7.0 配置 <system.webServer> 节

    https://technet.microsoft.com/zh-cn/sysinternals/bb763179.aspx https://www.cnblogs.com/tl2f/p/501615 ...

随机推荐

  1. Vue3 基础概念与环境搭建

    前言 首先需要提醒大家的是,Vue2 已经在2023年停止维护,为了能更好地适应前端开发的发展趋势以及获得更好的性能和功能,我们将从这篇文章开始进入Vue3的阶段.如果对Vue2有想了解的小伙伴可以自 ...

  2. 【Manim】空间与变换笔记

    [Manim]空间与变换笔记 所有常量都可以在constants.py中找到 屏幕空间 屏幕中心为原点(0,0,0),遵循右手坐标系,向右为x轴正方向,向上为y轴正方向,向前为z轴负方向,旋转时正方向 ...

  3. Zookeeper - [04] 分布式安装部署

    一.集群规划 序号 主机名 JDK Zookeeper 1 node01 ○ ○ 2 node02 ○ ○ 3 node03 ○ ○ 二.安装部署 1.将zookeeper安装包解压到合适的目录,如/ ...

  4. [rustGUI][iced]基于rust的GUI库iced(0.13)的部件学习(06):基于iced实现一个简单的图片浏览器

    前言 本文是关于iced库的部件介绍,iced库是基于rust的GUI库,作者自述是受Elm启发. iced目前的版本是0.13.1,相较于此前的0.12版本,有较大改动. 本合集是基于新版本的关于分 ...

  5. VScode美化

    RESULT:EVA-初号机 配色 主题效果 1. 需要的东西 vs code background 插件 custom CSS and JS loader 插件 一些png素材,推荐网址: http ...

  6. 附035.Kubernetes_v1.25.3高可用部署架构二

    目录 部署组件 kubeadm介绍 kubelet介绍 kubectl介绍 方案概述 方案介绍 部署规划 节点规划 主机名配置 变量准备 互信配置 环境初始化 部署高可用组件 HAProxy安装 Ke ...

  7. Qt QCheckBox设置复选框的大小

    文章目录 Qt设计QCheckBox样式表 QCheckBox的各部分代表的样式表 Qt QCheckBox设置复选框的大小 Qt设计QCheckBox样式表 QCheckBox的各部分代表的样式表 ...

  8. linux部署go项目

    直接部署: 1.将程序所需要的文件如配置文件和生成的可执行文件拷贝到linux中 2.直接执行./main命令,启动程序 (main是go编译生成的可执行文件) 如果报Permission denie ...

  9. 性能优化之使用HTTP2.0

    HTTP2.0 的优势 配置 测试 怎么查看当前网站http版本 chrome HTTP协议版本检测 Chrome 控制台 window.chrome.loadTimes() { commitLoad ...

  10. while(bug)

    while(bug) { // 加了班也不一定写的完代码 // 写完了代码也不一定编译的过 // 编译过了也不一定没bug // 有了bug也不一定找的到 // 找到bug也不一定改的了 // 改了这 ...