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

运行Flask调用OpenWeather API时出现KeyError: 'main'错误如何解决

错误触发原因
  • API请求参数构造错误:代码中查询参数写为q=city{city},{country},多余拼接了city前缀,导致OpenWeather无法识别查询的城市,返回的错误响应体中无main字段,直接读取就会触发KeyError。
  • 缺少必要的请求校验与异常捕获:未判断API请求是否成功,也没有做字段存在性校验,请求失败时直接读取不存在的字段必然报错。
修复方案

需要做三处修改:

  1. 修正API查询参数,删除多余的city前缀
  2. 新增请求状态校验,请求失败时返回浏览器端友好提示
  3. 新增字段安全读取逻辑,避免KeyError

修复后的完整代码如下:

from wap import app
from flask import render_template, request
import requests

@app.route('/', methods=['GET', 'POST'])
def create_app():
    if request.method == 'POST':
        city = request.form['city']
        country = request.form['country']
        api_key = '#########################'

        # 修正q参数的拼写错误
        weather_resp = requests.get(
            f'http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q={city},{country}&units=metric'
        )

        # 校验API请求是否成功
        if weather_resp.status_code != 200:
            err_msg = "天气查询失败,请检查输入的城市、国家是否正确后重试"
            return render_template('index.html', err_msg=err_msg)
        
        weather_data = weather_resp.json()
        main_data = weather_data.get('main')
        wind_data = weather_data.get('wind')

        # 校验返回字段是否完整
        if not main_data or not wind_data:
            err_msg = "未查询到对应城市的有效天气数据"
            return render_template('index.html', err_msg=err_msg)

        # 安全读取字段
        temp = round(main_data.get('temp', 0))
        humidity = main_data.get('humidity', 0)
        wind_speed = wind_data.get('speed', 0)

        return render_template('result.html', temp=temp, humidity=humidity, wind_speed=wind_speed, city=city)
    return render_template('index.html')

你可以在index.html中新增错误提示的展示位置,所有报错信息都会直接在浏览器端展示,无需终端打印。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:15:04