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

OpenWeatherMap API调用触发KeyError: 'daily'问题求助

问题排查与修复方案

核心问题分析

从你提供的forecast_response可以看到,API返回了401未授权错误,说明请求One Call API时密钥验证失败,此时响应里根本没有daily字段,直接访问forecast_response['daily']自然会触发KeyError。

分步修复步骤

1. 解决API密钥认证问题

即便你说已核对过密钥,仍需确认以下几点:

  • 确认你的API密钥是否启用了One Call API 3.0的访问权限(部分免费账户需手动启用,该API可能需要付费订阅)
  • 检查密钥是否复制错误:比如首尾是否有空格、大小写是否匹配(OpenWeatherMap密钥区分大小写)
  • 确认账户状态正常,未超出API调用限额

2. 添加错误处理,避免KeyError

无论API是否正常响应,都应先检查状态码并处理错误,修改后的代码如下:

import requests
import datetime

def fetch_weather_and_forecast(city, api_key, current_weather_url, forecast_url):
    # 获取当前天气并处理错误
    current_response = requests.get(current_weather_url.format(city, api_key))
    if current_response.status_code != 200:
        raise Exception(f"获取当前天气失败: {current_response.json().get('message', '未知错误')}")
    current_data = current_response.json()
    
    lat, lon = current_data['coord']['lat'], current_data['coord']['lon']
    
    # 获取预报数据并处理认证/其他错误
    forecast_response = requests.get(forecast_url.format(lat, lon, api_key))
    if forecast_response.status_code != 200:
        error_msg = forecast_response.json().get('message', '获取预报失败')
        raise Exception(f"获取天气预报失败: {error_msg}")
    forecast_data = forecast_response.json()

    weather_data = {
        'city': city,
        'temperature': round(current_data['main']['temp'] - 273.15, 2),
        'description': current_data['weather'][0]['description'],
        'icon': current_data['weather'][0]['icon'],
    }

    daily_forecasts = []
    # 安全访问daily字段
    for daily_data in forecast_data['daily'][:5]:
        daily_forecasts.append({
            'day': datetime.datetime.fromtimestamp(daily_data['dt']).strftime('%A'),
            'min_temp': round(daily_data['temp']['min'] - 273.15, 2),
            'max_temp': round(daily_data['temp']['max'] - 273.15, 2),
            'description': daily_data['weather'][0]['description'],
            'icon': daily_data['weather'][0]['icon'],
        })

    return weather_data, daily_forecasts

3. 额外优化建议

  • 将错误处理封装为独立函数,减少代码重复
  • 添加请求超时设置:requests.get(..., timeout=10),避免请求长时间挂起
  • 定义温度转换常量KELVIN_TO_CELSIUS = 273.15,提升代码可读性

验证方法

  1. 用curl或Postman直接调用替换参数后的forecast_url,确认是否能返回包含daily字段的正常响应
  2. 运行修改后的代码,若密钥仍有问题,会抛出明确的错误信息,而非KeyError

内容的提问来源于stack exchange,提问作者Akshay Kumar Dubey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 19:06:27