赞
踩
关于请求的操作,比如从URL中提取路径参数,获取查询参数,获取请求头,获取Cookie,获取请求体中的数据;这些参数和值的获取非常方便,这是因为FastAPI帮我们创造便利。
FastAPI底层依赖Starlette,本质上是FastAPI帮我们做了一些操作,从Starlette的Request对象解析出上述各个参数。
所以,对于上面这些常用的请求参数,我们可以直接使用FastAPI给我们提供的工具,并且有了数据校验、类型转化、OPenAPI文档等功能。
当然了,你不使用FastAPI提供的便捷工具,直接从Request对象中解析数据也是可以的,但就没由数据校验、类型转化、OPenAPI文档等功能。
不过,有些场景,比如说获取请求的IP,请求的client host等等,那我们就必须直接使用Request对象。
示例1:使用使用Request获取常见参数
from fastapi import FastAPI, Request from starlette.requests import Request app = FastAPI() @app.get("/{item_id}") def hello(req: Request): item_id = req.path_params.get("item_id") page = req.query_params.get("page", 0) size = req.query_params.get("size", 10) x_token = req.headers.get("x-token") x_token_cookie = req.cookies.get("x_token") return { "item_id": item_id, "page": page, "size": size, "x-token": x_token, "cookie": x_token_cookie, }
示例2:使用Request获取客户端host
Request
对象,或者直接从 starlette.requests导入 Request
, 两者是一样的效果。item_id
是用的FastAPI提供的便捷方式,所以具有类型转换、类型校验、openapi文档等附加功能。req
的类型是 Request
,那FastAPI就知道要直接从Request中获取参数,就没有上述附加功能。from fastapi import FastAPI, Request
from starlette.requests import Request
app = FastAPI()
@app.get("/item/{item_id}")
def hello(item_id: int, req: Request):
return {
"item_id": item_id,
"client_host": req.client.host
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。