14.FastAPI响应头

14.1通过Response参数设置

可以通过Response参数的headers来设置标头。代码如下:

from fastapi import FastAPI
from fastapi import Response
​
app = FastAPI()
​
@app.get(path='/test')
async def hello(response: Response):
    response.headers['X-Cat-Dog'] = 'world'
    return {'hello': 'world'}

执行请求:

curl http://127.0.0.1:8000/test -i
HTTP/1.1 200 OK
date: Tue, 18 Jan 2022 00:47:32 GMT
server: uvicorn
content-length: 17
content-type: application/json
x-cat-dog: world
​
{"hello":"world"}

14.2直接返回Response

可以直接返回一个设置好标头的Response,代码如下:

from fastapi import FastAPI
from fastapi.responses import JSONResponse
​
app = FastAPI()
​
@app.get(path='/test')
async def hello():
    data = {'hello': 'world'}
    headers = {'X-Cat-Dog': 'world'}
    return JSONResponse(content=data, headers=headers)

执行请求:

curl http://127.0.0.1:8000/test -i
HTTP/1.1 200 OK
date: Tue, 18 Jan 2022 00:53:32 GMT
server: uvicorn
x-cat-dog: world
content-length: 17
content-type: application/json
​
{"hello":"world"}
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐