能否自动填充Open-Meteo的经纬度?API调用问题求助
解决Open-Meteo API经纬度自动填充问题
问题分析
原代码存在两个关键问题:
- 代码顺序错误:先构造了请求URL,之后才从数据库获取经纬度变量,导致URL无法获取到正确值
- 参数值未替换:URL中的
latitude=latitude是将字符串"latitude"作为参数传递,而非你从数据库取出的变量值
可行解决方法
方法1:使用Python f-string格式化URL
先获取经纬度变量,再用f-string将变量直接插入URL,语法简洁直观:
# 先从数据库获取经纬度 latitude = self.get_latitude() longitude = self.get_longitude() # 用f-string将变量填充到URL对应位置 url = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&hourly=temperature_2m&daily=temperature_2m_max,temperature_2m_min&timezone=auto&forecast_days=16" response = requests.get(url) response_json = response.json() # 提取并展示气温数据示例:获取当日最高、最低温 if "daily" in response_json: max_temp = response_json["daily"]["temperature_2m_max"][0] min_temp = response_json["daily"]["temperature_2m_min"][0] print(f"目标地区当日最高气温:{max_temp}℃,最低气温:{min_temp}℃")
方法2:使用requests的params参数(推荐)
这种方式更规范,requests会自动处理参数编码和URL拼接,避免手动拼接URL时出现格式错误:
# 获取经纬度变量 latitude = self.get_latitude() longitude = self.get_longitude() # 定义API基础地址和参数字典 base_url = "https://api.open-meteo.com/v1/forecast" params = { "latitude": latitude, "longitude": longitude, "hourly": "temperature_2m", "daily": "temperature_2m_max,temperature_2m_min", "timezone": "auto", "forecast_days": 16 } # 传递params参数发起请求 response = requests.get(base_url, params=params) response_json = response.json() # 提取并展示气温数据示例:获取当日前6小时的逐小时气温 if "hourly" in response_json: temps = response_json["hourly"]["temperature_2m"] times = response_json["hourly"]["time"] for time, temp in zip(times[:6], temps[:6]): print(f"{time}:{temp}℃")
方法3:使用str.format()方法
适合Python 3.5及以下版本(f-string为Python 3.6+新增语法):
latitude = self.get_latitude() longitude = self.get_longitude() # 用占位符{}标记变量位置,再通过format传入对应值 url = "https://api.open-meteo.com/v1/forecast?latitude={}&longitude={}&hourly=temperature_2m&daily=temperature_2m_max,temperature_2m_min&timezone=auto&forecast_days=16".format(latitude, longitude) response = requests.get(url) response_json = response.json() # 数据展示逻辑可参考上述示例
注意事项
- 确保
self.get_latitude()和self.get_longitude()返回的是数值类型(float或int),而非字符串,否则可能导致API请求失败 - 可添加异常处理逻辑,捕获请求超时、JSON解析失败等情况,提升代码稳定性
内容的提问来源于stack exchange,提问作者Toothywhisperer 93
相关产品推荐
相关产品推荐

