Skip to Content
cwa
Advanced

Clients and caching

Reuse connections, query asynchronously, and configure HTTP clients and caching.

Module functions such as cwa.weather.get() are the easiest start, but each call opens a new connection and shares no cache. For many queries, server use or async code, use a client.

UseBest for
Module functions, such as cwa.weather.get()Scripts, occasional queries
CWAMany queries in one program, caching or custom settings
AsyncCWAasyncio code, such as FastAPI and other async web frameworks

Client

CWA has the same resources as the module functions, such as client.weather and client.forecast, used the same way:

from cwa import CWA

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

Use it with with so the connection closes when you are done. Without with, call client.close() yourself. Calls after closing raise ClientClosedError.

ParameterDefaultMeaning
api_keyThe CWA_API_KEY environment variableAPI key
timeout30 secondsTimeout for one request
retries3Retries after network or server errors
cacheTrueIn-memory caching; see Caching
max_concurrency8Maximum simultaneous requests in a batch
http_clientNoneYour own HTTP client; see Custom HTTP client

Async

AsyncCWA has the same methods as CWA, awaited:

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())

Caching

Each client keeps up to 64 MiB of responses in memory, so repeating a query for the same dataset shortly afterwards makes no new request. The cache is never written to disk, is freed when the client closes, and is separate for each API key.

CWA responses do not say how long they may be cached, so the SDK sets a limit by data type:

DatasetsReused for at most
Forecasts (F-)10 minutes
Observations (O-)5 minutes
Earthquakes (E-)1 minute
Warnings and typhoons (W-)Not cached
Other datasets1 minute

To always get fresh data, disable it with CWA(cache=False).

Custom HTTP client

For a proxy, custom certificates or other network settings, pass an httpx2.Client you created (httpx2.AsyncClient for async):

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("臺北市信義區")

You manage that HTTP client:

ConcernBehavior
ClosingThe SDK does not close it; close it yourself
TimeoutSet it on the HTTP client; also passing timeout= raises ConfigurationError
CachingThe SDK does not add caching; configure a hishel.httpx2 cache transport on it if needed. Also passing cache=True raises ConfigurationError