FastAPI变量查询参数 [英] FastAPI variable query parameters

查看:649
本文介绍了FastAPI变量查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个快速API服务器,该服务器接受请求,检查用户是否被授权,如果成功,则将其重定向到另一个URL.

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

我需要保留URL参数,例如

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

http://localhost:80/data/?param1 = val1& param2 = val2 应该重定向到 http://some.other.api/?param1 = val1& param2 = val2 ,从而保留先前分配的参数.

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.

我该如何实现?

代码:

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

推荐答案

在文档中,他们谈论:

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

这篇关于FastAPI变量查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆