Flask天气页面未输入城市却提前显示API数据问题求助
解决Flask表单未输入城市时自动加载数据的问题
问题根源
你的代码核心问题是不管是GET请求(打开页面)还是POST请求(提交表单),都会执行OpenWeatherMap的API调用。当打开页面时,city变量为None,此时构建的请求URL中q=None,部分API可能返回默认城市数据,或错误处理逻辑未覆盖该场景,导致页面直接渲染了数据。
解决方法
通过以下调整,确保仅在用户提交有效城市名时才触发API请求,同时优化模板的条件渲染逻辑:
重构后的Flask代码
@app.route('/weather', methods=['GET', 'POST']) def weather(): API_KEY = "xxxxx" BASE_URL = "https://api.openweathermap.org/data/2.5/weather" city = None temperature = None weather_desc = None clothing = None error_msg = None if request.method == 'POST': city = request.form.get("city", "").strip() # 校验城市名是否为空 if city: request_url = f"{BASE_URL}?lang=fr&appid={API_KEY}&q={city}" response = requests.get(request_url) if response.status_code == 200: data = response.json() weather_desc = data["weather"][0]["description"] temperature = round(data["main"]["temp"] - 273.15, 2) # 修正穿着判断逻辑(原逻辑存在条件覆盖问题) if temperature > 17.00: clothing = "t-shirt" elif 5.00 < temperature <= 17.00: clothing = "Cotton ouaté ou une petite veste" elif temperature <= 5.00: clothing = "Un bon manteau chaud!" else: error_msg = "无法获取该城市的天气数据,请检查城市名是否正确" else: error_msg = "请输入城市名" # 统一渲染模板,根据变量状态显示对应内容 return render_template("weather.html", city=city, temperature=temperature, weather=weather_desc, clothing=clothing, error_msg=error_msg)
对应HTML模板调整
<form method="POST"> <input type="text" name="city" placeholder="输入城市名"> <button type="submit">查询天气</button> </form> {% if error_msg %} <p style="color: red;">{{ error_msg }}</p> {% endif %} {% if city and temperature %} <h2>{{ city }} 的天气</h2> <p>天气状况: {{ weather }}</p> <p>温度: {{ temperature }}°C</p> <p>推荐穿着: {{ clothing }}</p> {% endif %}
关键优化点
- API请求逻辑仅在有效POST请求时执行:只有用户提交表单且输入了城市名,才会调用天气API,避免打开页面时自动触发请求
- 增加空值校验:防止用户提交空表单导致的无效API请求
- 模板条件渲染:通过Jinja的
{% if %}判断,仅当存在有效数据时才显示天气信息,否则只展示表单和错误提示 - 修正穿着判断逻辑:原代码中
<=17.00的条件会覆盖<=5.00的场景,调整后确保每个温度区间的判断准确
内容的提问来源于stack exchange,提问作者OldLadyCoding
相关产品推荐
相关产品推荐

