# 示例代码:使用 Python 调用 API 并处理响应
import requests
def get_weather(city):
# 定义 API 的 URL 和参数
url = "http://api.weatherapi.com/v1/current.json"
params = {
'key': 'your_api_key_here', # 替换为你的 API 密钥
'q': city
}
# 发送 GET 请求
response = requests.get(url, params=params)
# 检查响应状态码
if response.status_code == 200:
data = response.json()
# 解析并返回天气信息
weather_info = {
'temperature': data['current']['temp_c'],
'condition': data['current']['condition']['text']
}
return weather_info
else:
return f"Error: Unable to fetch data. Status code: {response.status_code}"
# 示例调用
city = "London"
weather = get_weather(city)
print(f"Weather in {city}: {weather['temperature']}°C, {weather['condition']}")
requests 库:用于发送 HTTP 请求。get_weather 函数:该函数接受一个城市名称作为参数,并调用天气 API 获取当前天气信息。requests.get 方法发送请求,并传递 URL 和参数。get_weather 函数并打印结果。请确保你已经安装了 requests 库,可以通过以下命令安装:
pip install requests
上一篇:python批量注释
下一篇:python ui
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站