FastAPI重定向响应自定义头

2024-09-24 00:35:20 发布

您现在位置:Python中文网/ 问答频道 /正文

基于my previous question,我现在需要向响应添加一个头

根据the documentation,我可以简单地向RedirectResponse对象添加头和另一个属性

当我测试这个时,它似乎没有把头的值带过

根据this post,不可能为重定向请求设置头。所以我应该试试别的方法,而不是重定向

有什么想法吗

from fastapi import FastAPI, Request
from starlette.responses import RedirectResponse

app = FastAPI()

@app.get("/data/")
async def api_data(request: Request):
    params = str(request.query_params)
    url = f'http://some.other.api/{params}'
    headers = {'Authorization': "some_long_key"}
    response = RedirectResponse(url=url, headers=headers)
    return response

Tags: fromimportapiappurldataresponserequest
1条回答
网友
1楼 · 发布于 2024-09-24 00:35:20

一种解决方案是在应用程序中执行请求,然后返回响应

但是这是非常低效的,将强制所有流量通过此服务器,而重定向将减少网络负载

import requests
from fastapi import FastAPI, Request, Response

app = FastAPI()

@app.get("/data/")
async def api_data(request: Request):
    params = str(request.query_params)
    url = f'http://some.other.api/{params}'
    headers = {'Authorization': "some_long_key"}
    r = requests.get(url, headers=headers)
    return Response(content=r.content)

相关问题 更多 >