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

Flask如何使用POST方法跨页面获取并展示数据

问题根因

你的代码一共有3处直接导致传值失败的错误:

  • 表单输入框的name属性与后端取值键名不匹配:后端用request.form['city_name']取值,但输入框name写的是text,提交时根本不会携带city_name字段,会直接触发400错误。
  • 表单action配置错误:你把提交地址直接指向结果页路由,还试图在渲染搜索页时就传入city_name参数,但这个值是用户提交后才能拿到的,渲染搜索页时不存在该变量,会触发模板渲染错误;同时你的结果页路由仅支持GET请求,直接接收POST表单会触发405方法不允许错误。
  • 结果页地理编码逻辑硬编码了城市名:就算传值成功,geolocator.geocode("Hyderabad")永远只会查询海得拉巴的坐标,不会使用传入的city_name参数。
修复方案

按照你原本想用的「表单提交到搜索路由→重定向带参到结果页」的逻辑,直接修改对应代码即可:

修正后的后端路由代码

from flask import request, redirect, url_for, render_template
from geopy.geocoders import Nominatim
import time
from datetime import date

@views.route('/search', methods=["GET", "POST"])
def search():
    if request.method == "POST":
        # 增加空值容错,避免用户空提交报错
        city_name = request.form.get('city_name', '').strip()
        if not city_name:
            return redirect(url_for("views.search"))
        return redirect(url_for("views.results", city_name=city_name))
    return render_template("search.html")


@views.route('/results/<city_name>')
def results(city_name):
    geolocator = Nominatim(user_agent="MyApp")
    # 替换硬编码的城市名,使用传入的参数
    location = geolocator.geocode(city_name)
    # 增加查询失败容错
    if not location:
        return f"未找到「{city_name}」对应的地理位置,请返回重新搜索"
    latitude = location.latitude
    longitude = location.longitude
    t = time.localtime()
    current_time = time.strftime("%I:%M", t)
    today = date.today()
    d4 = today.strftime("%b-%d-%Y")
    HTML_current_time = f"{current_time} {d4}"
    
    return render_template("results.html", current_time=HTML_current_time, latitude=latitude, longitude=longitude, city_name=city_name)

修正后的搜索页表单代码

<!-- 表单提交到search路由处理,不需要提前传city_name -->
<form action="{{ url_for('views.search') }}" method="post">
    <!-- name属性和后端取值键名保持一致 -->
    <input type="text" name="city_name" id="search" placeholder="Enter the place area...">
    <button type="submit" class="btn">
        <img src="/static/images/search.png" alt="搜索">
    </button>
</form>
排查参考

后续遇到Flask表单传值类问题,可以按以下顺序自查:

  • 表单输入项的name属性必须和后端request.form读取的键名完全一致,大小写敏感
  • 模板中调用url_for时传入的参数,必须是当前模板渲染时已存在的变量,用户提交后才生成的值不能提前写在表单action里
  • 接收请求的路由必须在methods参数中声明支持的请求方法,未声明POST的路由无法直接接收表单提交
  • 所有外部传入的参数(表单值、URL参数)都要做非空、合法性校验,避免无效参数触发代码报错
  • 确认业务逻辑中实际使用了传入的参数,不要出现硬编码默认值导致传参不生效的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 18:06:18