FastAPI variable query parameters

浪尽此生 提交于 2020-06-17 09:09:24

问题


I am writing a Fast API server that accepts requests, checks if users are authorized and then redirects them to another url if successful.

I need to carry over URL parameters, e.g.

http://localhost:80/data/?param1=val1&param2=val2 should redirect to http://some.other.api/?param1=val1&param2=val2, thus keeping previously allotted parameters.

There parameters are not controlled by me and could change at any moment.

How can I achieve this?

Code:

from fastapi import FastAPI
from starlette.responses import RedirectResponse

app = FastAPI()

@app.get("/data/")
async def api_data():
    params = '' # I need this value
    url = f'http://some.other.api/{params}'
    response = RedirectResponse(url=url)
    return response


回答1:


In the docs they talk about using the Request directly, which then lead me to this:

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}'
    response = RedirectResponse(url=url)
    return response


来源:https://stackoverflow.com/questions/62279710/fastapi-variable-query-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!