fastapi 模式的额外信息,示例 / Cookie参数 / Header参数

简介: fastapi 模式的额外信息,示例 / Cookie参数 / Header参数

文章目录

1. Pydantic schema_extra

2. Field 的附加参数

3. Body 额外参数

4. Cookie 参数

5. Header 参数

5.1 重复的 headers

learn from https://fastapi.tiangolo.com/zh/tutorial/schema-extra-example/


添加一个将在文档中显示的 example


1. Pydantic schema_extra

from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None
    class Config:
        schema_extra = {
            "example": {
                "name": "michael",
                "description": "a learner",
                "price": 100.0, 
                "tax": 0.1
            }
        }
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    res = {"item_id": item_id, "item": item}
    return res

image.pngimage.png

其中: class Config:

schema_extra = {

example”: {

加黑的字符,大小写必须完全一致,应该是内置的字段,否则无法显示例子


2. Field 的附加参数


  • Field(None, example=xxx)
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
    name: str = Field(..., example="michael")
    description: Optional[str] = Field(None, example="handsome")
    price: float = Field(..., example=34.5)
    tax: Optional[float] = Field(None, example=0.1)
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    res = {"item_id": item_id, "item": item}
    return res

image.png


3. Body 额外参数


可以通过传递额外信息给 Field 同样的方式操作Path, Query, Body

from typing import Optional
from fastapi import FastAPI, Body
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None
@app.put("/items/{item_id}")
async def update_item(
    item_id: int, 
    item: Item = Body(
        ...,
        example = {  # 加入 example 参数
            "name": "michael",
            "description": "a learner",
            "price": 100.1, 
            "tax": 0.1
        }
    )
):
    res = {"item_id": item_id, "item": item}
    return res


4. Cookie 参数


声明 Cookie 参数的结构与声明 Query 参数和 Path 参数时相同。

第一个值是参数的默认值,同时也可以传递所有验证参数或注释参数,来校验参数

你需要使用 Cookie 来声明 cookie 参数,否则 参数将会被解释为 查询参数

from typing import Optional
from fastapi import Cookie, FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(ads_id: Optional[str] = Cookie(None)):
    return {"ads_id": ads_id} 

使用 postman 测试

image.pngimage.pngimage.png


5. Header 参数


大多数标准的 headers 用 "连字符" 分隔,也称为 "减号" (-)。


但是像 user-agent 这样的变量在Python中是无效的。


因此, 默认情况下, Header 将把参数名称的字符从下划线 (_) 转换为连字符 (-) 来提取并记录 headers


如果需要禁用 下划线到连字符 的自动转换,设置 Header 的参数 convert_underscores 为 False

注意:一些 HTTP 代理和服务器不允许使用带有下划线的 headers

from typing import Optional
from fastapi import Cookie, FastAPI, Header
app = FastAPI()
@app.get("/items/")
async def read_items(my_agent: Optional[str] = Header(None)):
    return {"my_agent": my_agent}    

image.png

from typing import Optional
from fastapi import Cookie, FastAPI, Header
app = FastAPI()
@app.get("/items/")
async def read_items(my_agent: Optional[str] = Header(None, convert_underscores=False)):
    return {"my_agent": my_agent} 

image.png


5.1 重复的 headers


可以通过一个Python list 的形式获得 重复header 的 所有值

from typing import Optional, List
from fastapi import Cookie, FastAPI, Header
app = FastAPI()
@app.get("/items/")
async def read_items(x_token: Optional[List[str]] = Header(None)):
    return {"x_token value:": x_token} 

image.png

相关文章
|
11月前
|
前端开发
解决前端ajax跨域请求不携带cookie信息JSESSIONID的问题
解决前端ajax跨域请求不携带cookie信息JSESSIONID的问题
|
2月前
|
数据采集 Web App开发 API
FastAPI与Selenium:打造高效的Web数据抓取服务 —— 采集Pixabay中的图片及相关信息
本文介绍了如何使用FastAPI和Selenium搭建RESTful接口,访问免版权图片网站Pixabay并采集图片及其描述信息。通过配置代理IP、User-Agent和Cookie,提高爬虫的稳定性和防封禁能力。环境依赖包括FastAPI、Uvicorn和Selenium等库。代码示例展示了完整的实现过程,涵盖代理设置、浏览器模拟及数据提取,并提供了详细的中文注释。适用于需要高效、稳定的Web数据抓取服务的开发者。
144 15
FastAPI与Selenium:打造高效的Web数据抓取服务 —— 采集Pixabay中的图片及相关信息
|
6月前
|
缓存 Java Spring
servlet和SpringBoot两种方式分别获取Cookie和Session方式比较(带源码) —— 图文并茂 两种方式获取Header
文章比较了在Servlet和Spring Boot中获取Cookie、Session和Header的方法,并提供了相应的代码实例,展示了两种方式在实际应用中的异同。
438 3
servlet和SpringBoot两种方式分别获取Cookie和Session方式比较(带源码) —— 图文并茂 两种方式获取Header
|
7月前
|
存储 缓存 数据处理
php学习笔记-php会话控制,cookie,session的使用,cookie自动登录和session 图书上传信息添加和修改例子-day07
本文介绍了PHP会话控制及Web常用的预定义变量,包括`$_REQUEST`、`$_SERVER`、`$_COOKIE`和`$_SESSION`的用法和示例。涵盖了cookie的创建、使用、删除以及session的工作原理和使用,并通过图书上传的例子演示了session在实际应用中的使用。
php学习笔记-php会话控制,cookie,session的使用,cookie自动登录和session 图书上传信息添加和修改例子-day07
|
8月前
|
数据安全/隐私保护
在某网站的登录页面登录时如果选择“记住用户名”,登录成功后会跳转到一个中间层(页面代码将登录的用户名和密码存在cookie),中间页面中存在一个超链接,单击超链接可以链接到第三个页面查看信息。若选择“
该博客文章通过示例代码和运行结果截图,展示了网站登录过程中如何通过中间层页面使用cookies技术实现“记住用户名”功能,并在点击超链接后查看保存的用户名和密码信息。
在某网站的登录页面登录时如果选择“记住用户名”,登录成功后会跳转到一个中间层(页面代码将登录的用户名和密码存在cookie),中间页面中存在一个超链接,单击超链接可以链接到第三个页面查看信息。若选择“
|
8月前
|
存储 C#
【Azure APIM】APIM 策略语句如何读取请求头中所携带的Cookie信息并保存为变量
【Azure APIM】APIM 策略语句如何读取请求头中所携带的Cookie信息并保存为变量
|
8月前
|
数据安全/隐私保护
|
8月前
|
开发框架 JSON API
Python中FastAPI项目使用 Annotated的参数设计
Python中FastAPI项目使用 Annotated的参数设计
|
10月前
|
安全 Java Maven
如何使用jsoup实现网站登录,cookie保存,查询信息
【6月更文挑战第11天】如何使用jsoup实现网站登录,cookie保存,查询信息
365 1
|
10月前
|
JSON 前端开发 Java
Spring第一课,了解IDEA里面的文件,回顾Cookie和Session,获取Session,Cookie,Header的方式
Spring第一课,了解IDEA里面的文件,回顾Cookie和Session,获取Session,Cookie,Header的方式