制作大模型获取天气数据工具(和风API)
先访问和风天气获取API
初始化API客户端
一些教程使用以下网站构造url将报错
"https://geoapi.qweather.com/v2/"
"https://api.qweather.com/v7/"
"https://devapi.qweather.com/v7/"
正确url构造格式为(your_api_host改为自己的):
"https://your_api_host/geo/v2/city/lookup?location=beij"
"https://your_api_host/v7/weather/now?location=101010100"
以下为2025.9.23的最新初始化和风天气API客户端
import time
import requests
import datetimeclass QWEATHER:_api_host = "输入你自己的API host"def __init__(self, api_key):self.API_KEY = api_keydef search_city(self, location):"""根据城市名称查询城市ID"""url = f"https://{self._api_host}/geo/v2/city/lookup"params = {"location": location}response = self.http_request_v2(url, method="GET", headers=self.headers(), params=params)if response and response.get("code") == "200" and response.get("location"):return response["location"][0]["id"] # 返回第一个匹配的城市IDreturn Nonedef get_current_weather(self, location_id):"""获取指定城市ID的当前天气"""url = f"https://{self._api_host}/v7/weather/now"params = {"location": location_id}response = self.http_request_v2(url, method="GET", headers=self.headers(), params=params)return response# 生成 headers 头def headers(self, params=None):headers = {'Content-Type': 'application/json','X-QW-Api-Key': f'{self.API_KEY}'}return headersdef http_request_v2(self, url, method="GET", headers={}, params=None, max_retries=2, timeout=3):headers = headers or {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'}headers.update(self.headers())for attempts in range(1, max_retries + 1):try:if method == "GET":response = requests.get(url, headers=headers, params=params, timeout=timeout)elif method in ("POST", "DELETE"):response = requests.request(method, url, json=params, headers=headers, timeout=timeout)response.raise_for_status()return response.json()except Exception as e:print([datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), attempts, url, method, params, headers, repr(e)])time.sleep(timeout * attempts)return None
格式化输出天气
def format_current_weather(response, city_name):"""格式化输出天气数据"""if not response or response.get("code") != "200":return f"无法获取{city_name}的天气,请稍后重试"else:now = response.get("now")update_time = response.get("updateTime", "").split("T")[1].split("+")[0] # 提取时间部分weather_info = f"{city_name}当前({update_time})的天气是{now.get('text', '未知')},"weather_info += f"气温{now.get('temp', '未知')}℃,"weather_info += f"{now.get('windDir', '未知')}{now.get('windScale', '未知')}级,"weather_info += f"湿度{now.get('humidity', '未知')}%"return weather_info
测试
if __name__ == '__main__':api_key = "输入你自己的APi keys"client = QWEATHER(api_key)city_name = input("请输入城市名称(例如:广州):").strip()city_id = client.search_city(city_name)if not city_id:print(f"未找到城市:{city_name},请检查")else:weather_response = client.get_current_weather(city_id)print(format_current_weather(weather_response, city_name))