# 用戶端與快取 (https://nolantw.github.io/cwa/advanced/clients/)

`cwa.weather.get()` 等模組函式最容易上手，但每次呼叫都會建立新的連線，也不會共用快取。查詢次數多、在伺服器中使用，或需要非同步時，改用用戶端。

| 使用方式 | 適合 |
| --- | --- |
| 模組函式，如 `cwa.weather.get()` | 腳本、偶爾查詢 |
| `CWA` | 同一段程式多次查詢、需要快取或調整設定 |
| `AsyncCWA` | asyncio 程式，例如 FastAPI 等非同步網頁框架 |

## 用戶端

`CWA` 提供與模組函式相同的資源，例如 `client.weather`、`client.forecast`，用法完全相同：

```python
from cwa import CWA

with CWA() as client:
    weather = client.weather.get("臺北市信義區")
    quake = client.earthquakes.latest()
```

請以 `with` 使用，離開時會關閉連線。不使用 `with` 時，用完要呼叫 `client.close()`。關閉後再呼叫會引發 `ClientClosedError`。

| 參數 | 預設 | 說明 |
| --- | --- | --- |
| `api_key` | 環境變數 `CWA_API_KEY` | 授權碼 |
| `timeout` | 30 秒 | 單次請求的逾時秒數 |
| `retries` | 3 | 網路錯誤或伺服器錯誤時的重試次數 |
| `cache` | `True` | 是否啟用記憶體快取，見[快取](#快取) |
| `max_concurrency` | 8 | 批次查詢時同時發出的請求數上限 |
| `http_client` | 無 | 自訂的 HTTP 用戶端，見[自訂 HTTP 用戶端](#自訂-http-用戶端) |

## 非同步

`AsyncCWA` 的方法與 `CWA` 相同，但需要 `await`：

```python
import asyncio
from cwa import AsyncCWA

async def main() -> None:
    async with AsyncCWA() as client:
        weather = await client.weather.get("臺北市信義區")
        print(weather.current)

asyncio.run(main())
```

## 快取

每個用戶端在記憶體中保留最多 64 MiB 的回應，短時間內重複查詢同一資料集時不會再次請求。快取不寫入磁碟，關閉用戶端時釋放，不同授權碼的快取互不共用。

氣象署的回應沒有標示可快取多久，因此 SDK 依資料類型設定上限：

| 資料集 | 重複使用上限 |
| --- | --- |
| 預報（`F-` 開頭） | 10 分鐘 |
| 觀測（`O-` 開頭） | 5 分鐘 |
| 地震（`E-` 開頭） | 1 分鐘 |
| 警特報及颱風（`W-` 開頭） | 不快取 |
| 其他資料集 | 1 分鐘 |

需要每次都取得最新資料時，以 `CWA(cache=False)` 停用。

## 自訂 HTTP 用戶端

需要代理伺服器、自訂憑證等進階網路設定時，可傳入自己建立的 `httpx2.Client`（非同步用戶端為 `httpx2.AsyncClient`）：

```python
import httpx2
from cwa import CWA

with httpx2.Client(proxy="http://proxy.example:8080", timeout=60) as http:
    with CWA(http_client=http) as client:
        weather = client.weather.get("臺北市信義區")
```

傳入的 HTTP 用戶端由你管理：

| 項目 | 行為 |
| --- | --- |
| 關閉 | SDK 不會關閉它，用完請自行關閉 |
| 逾時 | 在 HTTP 用戶端上設定；同時傳入 `timeout=` 會引發 `ConfigurationError` |
| 快取 | SDK 不會替它啟用快取；需要時在該用戶端設定 `hishel.httpx2` 的快取傳輸層。同時傳入 `cache=True` 會引發 `ConfigurationError` |