美文网首页前端框架
使用FastAPI进行URL重定向

使用FastAPI进行URL重定向

作者: SeanCheney | 来源:发表于2023-01-09 16:40 被阅读0次

代码示例都来自于FastAPI的官方文档。示例代码写的很好,基本复制一下就能用了。

第一种方法,是直接返回一个RedirectResponse对象,默认的HTTP码是307

from fastapi import FastAPI
from fastapi.responses import RedirectResponse

app = FastAPI()


@app.get("/typer")
async def redirect_typer():
    return RedirectResponse("https://typer.tiangolo.com")

也可以将RedirectResponse对象作为参数response_class的值:

from fastapi import FastAPI
from fastapi.responses import RedirectResponse

app = FastAPI()


@app.get("/fastapi", response_class=RedirectResponse)
async def redirect_fastapi():
    return "https://fastapi.tiangolo.com"

这样做的好处,是返回的就是URL字符串,可以很方便地用一个函数对其进行处理。

如果想换成其它的status_code,放到get函数中即可:

from fastapi import FastAPI
from fastapi.responses import RedirectResponse

app = FastAPI()


@app.get("/pydantic", response_class=RedirectResponse, status_code=302)
async def redirect_pydantic():
    return "https://pydantic-docs.helpmanual.io/"

以上就是官方文档提供的代码。为了使运行更为便捷,添加上main函数,完整代码如下所示:

# -*- coding: UTF-8 -*-
# main.py

import uvicorn
from fastapi import FastAPI
from fastapi.responses import RedirectResponse

app = FastAPI()

@app.get("/pydantic", response_class=RedirectResponse, status_code=302)
async def redirect_pydantic():
    return "https://pydantic-docs.helpmanual.io/"

if __name__ == '__main__':
    uvicorn.run(
        app='main:app',
        host="0.0.0.0",
        port=302,
        workers=4,
        reload=True,
        debug=True)

此时,在本机浏览器访问http://127.0.0.1:302/pydantic,网页就自动跳转到https://pydantic-docs.helpmanual.io/上了。

相关文章

  • 使用FastAPI进行URL重定向

    代码示例都来自于FastAPI的官方文档。示例代码写的很好,基本复制一下就能用了。 第一种方法,是直接返回一个Re...

  • Asp.Net Core Url Rewrite

    在《Asp.Net Core Url Redirect》中使用重定向解决Url问题,还是有些不理想:重定向的Url...

  • 解决Servlet重定向时url中文参数乱码问题

    问题 最近在开发中遇到了在Servelet中使用response.sendRedirect(url)进行页面重定向...

  • ModelAndView重定向带参数解决方法

    业务场景:SpringMVC项目使用ModelAndView进行重定向跳转到另外一个action时,需要在url后...

  • 使用NSURLSession进行重定向

    使用URLSession进行重定向 遵守代理如下,completionHandler(nil)则拦截重定向;

  • 反转URL

    1.从视图函数到url的转换叫反转URL 2.反转url的作用: 1)页面重定向时会使用url反转; 2)模版中一...

  • Apache .htaccess

    原文链接1原文链接2原文链接3原文链接4 URL 重定向 URL重定向(URL redirection,或称网址重...

  • URL重定向漏洞

    原文链接:秋水表哥博客 0X00: 什么是url重定向? URL重定向(URL redirection,或称网址重...

  • dianjo增删改查

    url views html url配置路径 页面的跳转 转换与url的重定向

  • Apache URL重定向配置专题

    Url重定向机制简述 Rewrite url重定向就是实现URL的跳转和隐藏真实地址,基于Perl语言的正则表达式...

网友评论

    本文标题:使用FastAPI进行URL重定向

    本文链接:https://www.haomeiwen.com/subject/gvrjcdtx.html