如何在带域名的FastAPI中获取当前路径? [英] How to get current path in FastAPI with domain?

查看:0
本文介绍了如何在带域名的FastAPI中获取当前路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用FastAPI编写的简单路由,如下所示

from fastapi import FastAPI

app = FastAPI()


@app.get("/foo/bar/{rand_int}/foo-bar/")
async def main(rand_int: int):
    return {"path": f"https://some-domain.com/foo/bar/{rand_int}/foo-bar/?somethig=foo"}

如何以编程方式获取当前路径

  • 域(some-domain.com)
  • 路径(/foo/bar/{rand_int}/foo-bar/)
  • 和查询参数(?somethig=foo)

url

我们可以使用Request.url-(starlette doc)接口获取各种推荐答案属性。要获取绝对URL,我们需要使用Request.url._url私有接口,如下所示

from fastapi import FastAPI, Request

app = FastAPI()


@app.get("/foo/bar/{rand_int}/foo-bar/")
async def main(rand_int: int, request: Request):
    return {"raw_url": request.url._url}

这篇关于如何在带域名的FastAPI中获取当前路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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