当前位置: 首页 > news >正文

FastAPI 构建 API 高性能的 web 框架(二)

上一篇 FastAPI 构建 API 高性能的 web 框架(一)是把LLM模型使用Fastapi的一些例子,本篇简单来看一下FastAPI的一些细节。
有中文官方文档:fastapi中文文档

假如你想将应用程序部署到生产环境,你可能要执行以下操作:

pip install fastapi

并且安装uvicorn来作为服务器:

pip install "uvicorn[standard]"

然后对你想使用的每个可选依赖项也执行相同的操作。


文章目录

  • 1 基础使用
    • 1.1 单个值Query的使用
    • 1.2 多个参数
    • 1.3 请求参数 Field
    • 1.4 响应模型`response_model`
    • 1.5 请求文件UploadFile
    • 1.6 CORS(跨域资源共享)
    • 1.7 与SQL 通信


1 基础使用

参考:https://fastapi.tiangolo.com/zh/tutorial/body-multiple-params/

1.1 单个值Query的使用

from typing import Unionfrom fastapi import FastAPI, Queryapp = FastAPI()@app.get("/items/")
async def read_items(q: Union[str, None] = Query(default=None, max_length=50)):results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}if q:results.update({"q": q})return results

这里Union[str, None] 代表参数q,可以是字符型也可以None不填,Query用来更多的补充信息,比如这个参数,默认值是None,最大长度50

1.2 多个参数

from typing import Annotatedfrom fastapi import FastAPI, Path
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):
# 检查项,不同key要遵从什么格式name: strdescription: str | None = None # 字符或者None都可以,默认Noneprice: floattax: float | None = None # 数值或者None都可以,默认None@app.put("/items/{item_id}")
async def update_item(item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)], # item_id是一个路径,通过Annotated需要两次验证,验证一,是否是整数型,验证二,数值大小 大于等于0,小于等于1000q: str | None = None, item: Item | None = None, # 格式遵从class Item类且默认为None
):results = {"item_id": item_id}if q:results.update({"q": q})if item:results.update({"item": item})return results

1.3 请求参数 Field

pydantic中比较常见

from typing import Annotatedfrom fastapi import Body, FastAPI
from pydantic import BaseModel, Fieldapp = FastAPI()class Item(BaseModel):name: strdescription: str | None = Field(default=None, title="The description of the item", max_length=300)# 跟Query比较相似,设置默认,title解释,最大长度300price: float = Field(gt=0, description="The price must be greater than zero")# price大于0,且是float形式tax: float | None = None@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):results = {"item_id": item_id, "item": item}return results

1.4 响应模型response_model

参考:https://fastapi.tiangolo.com/zh/tutorial/response-model/

from typing import Anyfrom fastapi import FastAPI
from pydantic import BaseModel, EmailStrapp = FastAPI()class UserIn(BaseModel):username: strpassword: stremail: EmailStrfull_name: str | None = Noneclass UserOut(BaseModel):username: stremail: EmailStrfull_name: str | None = None@app.post("/user/", response_model=UserOut)
async def create_user(user: UserIn) -> Any:return user

response_model是控制输出的内容,按照规定的格式输出,作用概括为:

  • 将输出数据转换为其声明的类型。
  • 校验数据。
  • 在 OpenAPI 的路径操作中为响应添加一个 JSON Schema。
  • 并在自动生成文档系统中使用。

1.5 请求文件UploadFile

https://fastapi.tiangolo.com/zh/tutorial/request-files/

from fastapi import FastAPI, File, UploadFileapp = FastAPI()@app.post("/files/")
async def create_file(file: bytes = File()):return {"file_size": len(file)}@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile):return {"filename": file.filename}

UploadFile 与 bytes 相比有更多优势:

  • 这种方式更适于处理图像、视频、二进制文件等大型文件,好处是不会占用所有内存;
  • 可获取上传文件的元数据;

1.6 CORS(跨域资源共享)

https://fastapi.tiangolo.com/zh/tutorial/cors/

你可以在 FastAPI 应用中使用 CORSMiddleware 来配置它。

  • 导入 CORSMiddleware。
  • 创建一个允许的源列表(由字符串组成)。
  • 将其作为「中间件」添加到你的 FastAPI 应用中。
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddlewareapp = FastAPI()origins = ["http://localhost.tiangolo.com","https://localhost.tiangolo.com","http://localhost","http://localhost:8080",
]app.add_middleware(CORSMiddleware,allow_origins=origins,allow_credentials=True,allow_methods=["*"],allow_headers=["*"],
)@app.get("/")
async def main():return {"message": "Hello World"}
  • allow_origins - 一个允许跨域请求的源列表。例如 [‘https://example.org’, ‘https://www.example.org’]。你可以使用 [‘*’] 允许任何源。

1.7 与SQL 通信

https://fastapi.tiangolo.com/zh/tutorial/sql-databases/

FastAPI可与任何数据库在任何样式的库中一起与 数据库进行通信。


http://www.lryc.cn/news/116616.html

相关文章:

  • 如何实现 Java SpringBoot 自动验证入参数据的有效性
  • golang学习随记
  • 【PCL-6】PCL基于凹凸型的分割算法(LCCP)
  • 多进程并发服务器
  • 2021秋招总结
  • Linux6.34 Kubernetes yaml文件详解
  • 防火墙笔记
  • 使用代码下载开源的大模型文件示例以及中文微调llama资源汇总:
  • Wav2vec2 论文阅读看到的一些问题
  • 爬虫学习记录(持续更新)
  • libevent源码学习1---创建event
  • Python类的设计
  • 微信小程序的项目解构
  • 【Archaius技术专题】「Netflix原生态」动态化配置服务之微服务配置组件变色龙
  • python条件分支和循环语句
  • 工具推荐:Wireshark网络协议分析工具(对比tcpdump)
  • [OnWork.Tools]系列 04-快捷启动
  • 如何将项目挂后台运行?【nohup和tmux】
  • 什么是进程、线程、协程
  • Python爬虫——selenium_访问元素信息
  • Linux 文件基本属性
  • CSS 盒模型是什么?它包含哪些属性?标准盒模型/怪异盒模型
  • VB+SQL光盘信息管理系统设计与实现
  • MySQL5.7数据库、Navicat Premium1.6可视化工具安装教程【详细教程】
  • JVM 调优实例
  • Python numpy中的correlate相关性详解
  • 用python实现xmind用例转换为excel/csv用例
  • 论文浅尝 | 面向多步推理任务专业化较小语言模型
  • 基于Java的新闻全文搜索引擎的设计与实现
  • golang 自定义exporter - 端口连接数 portConnCount_exporter