You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中如何通过Persons页面按钮调用根路由(Home页面)

FastAPI页面跳转"Method Not Allowed"问题解决示例

问题根源

该错误通常是因为跳转请求的HTTP方法(默认是GET)与路由定义允许的方法不匹配,比如路由只配置了POST方法,但浏览器跳转用的是GET请求。下面是完整的可行实现示例:


后端代码实现

from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
import mysql.connector

app = FastAPI()
# 指定模板文件所在目录,需提前创建templates文件夹
templates = Jinja2Templates(directory="templates")

# MySQL连接配置(替换为你的实际数据库信息)
db_config = {
    "host": "localhost",
    "user": "your_db_user",
    "password": "your_db_pwd",
    "database": "your_db_name"
}

# 根路由 - 接受GET请求,渲染home.html
@app.get("/")
async def home(request: Request):
    # 连接MySQL并查询数据
    conn = mysql.connector.connect(**db_config)
    cursor = conn.cursor(dictionary=True)
    cursor.execute("SELECT * FROM your_home_table LIMIT 10")  # 替换为你的查询语句
    query_data = cursor.fetchall()
    cursor.close()
    conn.close()
    return templates.TemplateResponse("home.html", {"request": request, "data": query_data})

# /home路由 - 与根路由功能一致,用于跳转兼容
@app.get("/home")
async def home_redirect(request: Request):
    return await home(request)

# /persons路由 - 接受GET请求,渲染persons.html
@app.get("/persons")
async def persons(request: Request):
    conn = mysql.connector.connect(**db_config)
    cursor = conn.cursor(dictionary=True)
    cursor.execute("SELECT * FROM your_persons_table")  # 替换为你的人员表查询语句
    persons_list = cursor.fetchall()
    cursor.close()
    conn.close()
    return templates.TemplateResponse("persons.html", {"request": request, "persons": persons_list})

前端模板文件

在项目根目录下创建templates文件夹,放入以下两个HTML文件:

home.html

<!DOCTYPE html>
<html>
<head>
    <title>首页</title>
</head>
<body>
    <h1>首页数据</h1>
    <ul>
        {% for item in data %}
            <li>{{ item.id }} - {{ item.title }}</li> <!-- 替换为你的表字段 -->
        {% endfor %}
    </ul>
    <a href="/persons">查看人员列表</a>
</body>
</html>

persons.html

<!DOCTYPE html>
<html>
<head>
    <title>人员列表</title>
</head>
<body>
    <h1>人员列表</h1>
    <ul>
        {% for person in persons %}
            <li>{{ person.id }} - {{ person.name }}</li> <!-- 替换为你的人员表字段 -->
        {% endfor %}
    </ul>

    <!-- 推荐用a标签跳转(默认GET请求,匹配路由配置) -->
    <a href="/">回到首页</a>
    <!-- 或者跳转到/home路由 -->
    <!-- <a href="/home">回到首页</a> -->

    <!-- 若用表单跳转,必须显式指定GET方法 -->
    <!-- <form action="/" method="GET">
        <button type="submit">回到首页</button>
    </form> -->
</body>
</html>

关键注意事项

  1. 所有用于页面跳转的路由必须用@app.get()装饰器,确保接受GET请求(浏览器地址栏访问、a标签跳转均为GET请求)。
  2. 若使用表单跳转,必须显式设置method="GET",因为表单默认提交方法是POST,会与仅接受GET的路由冲突。
  3. MySQL连接逻辑可根据实际需求优化,比如使用连接池减少重复连接开销。

内容的提问来源于stack exchange,提问作者Phlip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 06:41:07