fastapi基础

fastapi快速学习

例子

from fastapi import FastAPI, Form, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional

# 创建FastAPI应用实例
app = FastAPI(title="简单的FastAPI应用", version="1.0.0")

# 添加CORS中间件
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 允许所有来源,生产环境中应该设置具体域名
allow_credentials=True,
allow_methods=["*"], # 允许所有HTTP方法
allow_headers=["*"], # 允许所有请求头
)


# 定义JSON数据模型
class UserProfile(BaseModel):
username: str
email: str
age: int
bio: Optional[str] = None

class Product(BaseModel):
name: str
price: float
category: str
description: Optional[str] = None

# 根路径
@app.get("/")
async def read_root():
return {"message": "欢迎使用FastAPI!", "status": "运行中"}

# 接收JSON数据的接口
@app.post("/api/user")
async def create_user(user: UserProfile):
"""
接收JSON格式的用户数据
"""
return {
"message": "用户创建成功",
"user_data": user,
"status": "success"
}

@app.post("/api/product")
async def create_product(product: Product):
"""
接收JSON格式的产品数据
"""
return {
"message": "产品创建成功",
"product_data": product,
"product_id": 12345,
"status": "success"
}

# 接收form-data的接口
@app.post("/api/form/user")
async def create_user_form(
username: str = Form(...),
email: str = Form(...),
age: int = Form(...),
bio: Optional[str] = Form(None)
):
"""
接收form-data格式的用户数据
"""
return {
"message": "用户表单提交成功",
"form_data": {
"username": username,
"email": email,
"age": age,
"bio": bio
},
"status": "success"
}

@app.post("/api/form/upload")
async def upload_file(
title: str = Form(...),
description: Optional[str] = Form(None),
file: UploadFile = File(...)
):
"""
接收form-data格式数据,包含文件上传
"""
return {
"message": "文件上传成功",
"form_data": {
"title": title,
"description": description,
"filename": file.filename,
"content_type": file.content_type,
"file_size": len(await file.read()) if file else 0
},
"status": "success"
}

@app.post("/api/form/mixed")
async def mixed_form_data(
name: str = Form(...),
price: float = Form(...),
category: str = Form(...),
description: Optional[str] = Form(None),
image: Optional[UploadFile] = File(None)
):
"""
混合form-data:包含普通字段和可选文件
"""
file_info = None
if image:
content = await image.read()
file_info = {
"filename": image.filename,
"content_type": image.content_type,
"size": len(content)
}

return {
"message": "混合数据提交成功",
"product_info": {
"name": name,
"price": price,
"category": category,
"description": description
},
"file_info": file_info,
"status": "success"
}


if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)

理解

1、 title: str = Form(…),在 FastAPI 中,Form(...) 用于指定一个请求参数是通过表单提交的。... 表示这个字段是必填的,也就是说在请求中必须提供这个字段。

2、description: Optional[str] = Form(None) 表示 description 是一个可选字段。如果表单中没有提供 description,它的默认值是 None

3、file: UploadFile = File(...) 这一行的含义是,file 是一个通过表单上传的文件,并且它是一个必填字段

理解1接口的参数

在 FastAPI 中,接口的参数类型和格式是必需的。这是 FastAPI 的一个核心特性

name: str = Form(…)

参数:数据类型=请求数据

Form用于处理表单数据;

File用于处理上传的文件;UploadFile处理文件的类

Body用于处理请求体中的 JSON 数据;

Query用于处理查询参数;

Path用于处理 URL 路径参数;

Header用于从请求头部提取数据;

Cookie用于从请求的 Cookie 中提取数据

Depends用于依赖注入,可以提取依赖项。

理解2接口异步函数

接口函数

@app.get("/")
async def read_root():
return {"message": "欢迎使用FastAPI!", "status": "运行中"}

异步函数:使用 async def 使得接口处理变成异步处理,有助于提高并发性能。

还有

@app.post:处理 POST 请求用于提交数据
@app.put:处理 PUT 请求用于更新资源
@app.patch:处理 PATCH 请求用于部分更新资源
@app.delete:处理 DELETE 请求用于删除资源。
@app.head:处理 HEAD 请求用于获取资源的头部信息,类似于 GET 请求,但是响应体不包含数据。
@app.options:处理 OPTIONS 请求用于描述目标资源的通信选项,通常用于跨域请求(CORS)。
@app.trace:处理 TRACE 请求通常用于调试。

理解3类的定义

# 定义JSON数据模型

class UserProfile(BaseModel):
username: str
email: str
age: int
bio: Optional[str] = None

类的概念的运用,和java的springboot很像,其中Optional用来标记一个字段可以是某种类型或None;BaseModel是基本数据模型

理解4分类引入

分类,因为类似于springboot的类,用类来限制请求很好,类单独写一个文件里面引入更加方便

同级引入
project/

├── main.py
└── models.py
如下main.py 引入 models.py
from models import (
UserProfile, UserResponse, Product, ProductResponse
)

上级引入
project/

├── app/
│ ├── main.py
│ └── models.py

└── utils/
├── helpers.py
如下helpers.py 想引入 main.py
from ..app.main import (
UserProfile, UserResponse, Product, ProductResponse
)

其他的问ai好了。

理解5跨域

在 web 浏览器中,出于安全考虑,存在一个叫做 同源策略(Same-Origin Policy)的机制。这个机制规定了一个网站的脚本只能访问来自 相同源 的数据,不同源 的资源是无法直接访问的。

同源的定义是:如果两个 URL 的协议、域名(或 IP 地址)、端口号都相同,它们就是同源的。

跨域 就是我本地发起一个请求,服务器上面响应就是跨域

本地发起本地响应就是不跨域了