gpt4 book ai didi

python - FastAPI RedirectResponse 自定义 header

转载 作者:行者123 更新时间:2023-12-04 11:44:54 26 4
gpt4 key购买 nike

基于 my previous question ,我现在需要在响应中添加一个 header 。

根据 the documentation ,我可以简单地将标题和另一个属性添加到 RedirectResponse目的。

当我对此进行测试时,它似乎没有携带 header 值。

根据 this post ,无法为重定向请求设置 header 。所以,而不是重定向,也许我应该尝试其他方法?

有任何想法吗?

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

最佳答案

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

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

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)

关于python - FastAPI RedirectResponse 自定义 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62282100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com