# ===== CodeLab: Python 网络请求与 API 调用 =====
# 来源: https://aoerliang.dpdns.org/articles/python-web-requests
# 以下代码片段按文章出现顺序拼接, 共 6 段

# ----- 片段 1 (bash) -----
pip install requests

# ----- 片段 2 (python) -----
import requests

resp = requests.get("https://httpbin.org/get")
print(resp.status_code)   # 200
print(resp.json())        # 自动解析 JSON 响应

# ----- 片段 3 (python) -----
import requests

params = {"q": "python", "page": 2}
headers = {"User-Agent": "Mozilla/5.0"}
resp = requests.get(
    "https://api.example.com/search",
    params=params, headers=headers, timeout=10,
)
print(resp.url)  # 实际请求的完整 URL

# ----- 片段 4 (python) -----
import requests

payload = {"username": "ada", "password": "secret"}
resp = requests.post("https://httpbin.org/post", json=payload)
print(resp.json()["json"])  # 回显提交的数据

# ----- 片段 5 (python) -----
import requests

try:
    resp = requests.get("https://httpbin.org/status/404", timeout=5)
    resp.raise_for_status()   # 4xx/5xx 会抛出异常
except requests.RequestException as e:
    print("请求失败:", e)

# ----- 片段 6 (python) -----
import requests

url = "https://api.open-meteo.com/v1/forecast"
params = {
    "latitude": 39.9,
    "longitude": 116.4,
    "daily": "temperature_2m_max",
    "timezone": "Asia/Shanghai",
}
data = requests.get(url, params=params, timeout=10).json()
print(data["daily"]["temperature_2m_max"])  # [33.2, 31.5, ...]
