【问题标题】:FastAPI variable query parametersFastAPI 变量查询参数
【发布时间】:2020-09-28 11:02:09
【问题描述】:

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

我需要携带URL参数,例如

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

有些参数不是我控制的,随时可能改变。

我怎样才能做到这一点?

代码:

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

【问题讨论】:

标签: python fastapi


【解决方案1】:

在他们谈论using the Request directly 的文档中,然后将我带到this

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

app = FastAPI()

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

【讨论】:

  • 如果你想让每个参数都通过呢?有什么方法可以从字符串 params 中获取所有参数?
【解决方案2】:

正如 FastAPI https://fastapi.tiangolo.com/tutorial/query-params-str-validations/ 的文档中提到的那样。

 @app.get("/")
 def read_root(param1: Optional[str] = None, param2: Optional[str] = None):
     url = f'http://some.other.api/{param1}/{param2}'
     return {'url': str(url)}

输出

【讨论】:

  • 啊是的,这也可以,但不考虑可能传入的任何数量的参数
  • 也喜欢这个答案..这个答案有一个很好的用例......当我需要用查询参数做一些其他事情时
猜你喜欢
  • 2013-02-13
  • 1970-01-01
  • 2023-02-16
  • 2011-11-02
  • 2023-03-20
  • 2023-02-14
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
相关资源
最近更新 更多