Skip to main content

wr-meteo

面向 WR 气象 HTTP 服务的 Python 客户端:支持点位气象气象因子查询,提供同步 / 异步两种调用方式,响应解析为类型化的不可变 dataclass

特性

  • 接口:GET /point(点位气象)、GET /factor(气象因子)
  • 批量:传入 list[dict],并发请求,结果顺序与输入一致
  • 鉴权:api_key(Query)、bearer(Header)、任意自定义 Header 名、或 none(无认证)
  • factor 端点可配置:factor_path="/loss"
  • factor 响应字段兼容:weather_factor / weather_loss 均可解析
  • 每个方法均有 *_async 与同步版本(基于 asgiref
  • 请求失败时记录日志并返回安全默认值,不向上抛出 HTTP 异常

要求

  • Python >= 3.12

安装

pip install wr-meteo

本地开发:

git clone <your-repo-url>
cd wr-meteo
pip install -e .
# 或
uv sync

快速开始

from wr_meteo import MeteoClient

client = MeteoClient(
    base_url="https://meteo.example.com/api",
    auth="your-secret",
    auth_type="X-API-Key",  # 见下方「鉴权」
    timeout=12.0,
)

# 点位气象(同步)
meteo = client.get_point_meteo(lon=121.5, lat=31.2, ts=1714000000)
print(meteo.temp, meteo.wind.kts if meteo.wind else None)

# 气象因子(同步)
speed, weather_f, current_f, marine = client.get_meteo_factor(
    imo=9123456,
    ts=1714000000,
    lon=121.5,
    lat=31.2,
    speed_knots=12.0,
    bearing=90.0,
    laden=True,
    source="gfs",
)
print(speed, weather_f, current_f, marine.sig_wave.height)

异步

import asyncio
from wr_meteo import MeteoClient

async def main():
    client = MeteoClient("https://meteo.example.com/api", auth="secret", auth_type="api_key")
    meteo = await client.get_point_meteo_async(lon=121.5, lat=31.2, ts=1714000000)
    factor = await client.get_meteo_factor_async(
        imo=9123456, ts=1714000000, lon=121.5, lat=31.2,
        speed_knots=12.0, bearing=90.0, laden=True, source="gfs",
    )
    print(meteo, factor)

asyncio.run(main())

批量查询

入参为 字典列表,每个字典的 key 与对应单条接口的 query 参数一致;客户端并发发起多个 HTTP 请求,返回列表与输入一一对应

# 批量点位气象
points = [
    {"lon": 121.5, "lat": 31.2, "ts": 1714000000},
    {"lon": 122.0, "lat": 32.0, "ts": 1714003600},
]
results = client.get_point_meteo_batch(points)

# 批量气象因子(键名与 API query 一致;也支持 speed_knots 别名)
factors = client.get_meteo_factor_batch([
    {
        "imo": 9123456, "ts": 1714000000,
        "lon": 121.5, "lat": 31.2,
        "speed": 12.0, "bearing": 90.0,
        "laden": True, "source": "gfs",
    },
])

# 异步
results = await client.get_point_meteo_batch_async(points)

单条失败时,该位置返回与单条接口相同的安全默认值,不影响其它条目。

鉴权

构造参数 auth 为密钥或 token 字符串,auth_type 决定如何携带:

auth_type 行为 示例
"api_key"(默认) Query:?api_key=<auth> 内部 / 简单网关
"bearer" Header:Authorization: Bearer <auth> 开放平台、JWT
"none" 不携带任何认证信息 无需认证的开放 API
其它字符串 Header:<auth_type>: <auth> auth_type="X-API-Key"
# Query
MeteoClient(base_url, auth="secret", auth_type="api_key")

# Bearer
MeteoClient(base_url, auth="eyJhbGciOi...", auth_type="bearer")

# 自定义 Header
MeteoClient(base_url, auth="secret", auth_type="X-API-Key")

鉴权参数保存在 client.headers / client.params,每次请求与业务 query 合并({**client.params, ...});httpx 对同名 query 以本次请求为准。

API 说明

MeteoClient

构造参数 类型 说明
base_url str 服务根 URL,如 https://host/api(勿以 / 结尾,客户端会自动处理)
auth str API 密钥或 Bearer token
auth_type str 默认 "api_key",见上表
timeout float HTTP 超时秒数,默认 12.0
factor_path str factor 接口路径,默认 "/factor",可改为 "/loss"

get_point_meteo / get_point_meteo_async

  • 路径{base_url}/point
  • Querylon, lat, ts(Unix 时间戳,秒)
  • 返回PointMeteo

get_meteo_factor / get_meteo_factor_async

  • 路径{base_url}{factor_path},默认 /factor,可配置
  • Queryimo, ts, lon, lat, speed, bearing, laden, source
  • 返回MeteoResult,即
    Tuple[speed, weather_factor, current_factor, MarineMeteo]
返回值 含义
speed 修正后航速(节)
weather_factor 风浪因子
current_factor 海流因子
MarineMeteo 风 / 流 / 有效波等明细

get_point_meteo_batch / get_point_meteo_batch_async

  • 入参items: list[dict],每项需含 lon, lat, ts
  • 返回list[PointMeteo],与 items 等长、同序

get_meteo_factor_batch / get_meteo_factor_batch_async

  • 入参items: list[dict],每项需含
    imo, ts, lon, lat, speed, bearing, laden, source
    speed_knots 可作为 speed 别名)
  • 返回list[MeteoResult],与 items 等长、同序

响应 JSON 约定(摘要)

/pointPointMeteo 字段与 JSON 键一致,例如:

{
  "temp": 25.1,
  "wind": {"kts": 12.0, "degree": 90.0},
  "wave": {"sig": {"height": 2.1, "period": 8.0}},
  "current": {"kts": 0.5},
  "utc": "2024-04-25T12:00:00Z"
}

/factor → 顶层示例:

{
  "speed": 11.2,
  "weather_factor": -0.5,
  "current_factor": -0.3,
  "meteo": { ... }
}

也接受 weather_loss / current_loss 字段名(与 weather_factor / current_factor 等效,取优先出现的值)。

MarineMeteo.from_dict 会解析顶层 sig_wave,若无则从 meteo.wave.sig 读取(与点位接口嵌套结构兼容)。

数据模型

导出类型(均可从 wr_meteo 直接 import):

类型 用途
PointMeteo 点位全量气象(含 wind / wave / current
MarineMeteo 因子接口中的 meteo 子结构
WindData / WaveData / CurrentData / OceanWavesData 嵌套子结构

子结构字段均为 Optional,缺失时为 NoneMarineMeteo 内 wind/current/sig_wave 默认为空 dataclass)。

手动解析:

from wr_meteo import PointMeteo, MarineMeteo

PointMeteo.from_dict(payload)
MarineMeteo.from_dict(meteo_dict)

错误处理

  • 网络错误、超时、非 2xx:写 ERROR 日志,不抛异常
  • get_point_meteo* / 批量中对应项 → 空 PointMeteo()
  • get_meteo_factor* / 批量中对应项 → (speed, 0.0, 0.0, MarineMeteo())speed 取自请求参数)

建议开启日志排查:

import logging

logging.basicConfig(level=logging.INFO)
logging.getLogger("wr_meteo").setLevel(logging.DEBUG)

开发与发布

# 可编辑安装
pip install -e .

# 构建 wheel / sdist
uv build
# 或: pip install hatchling && python -m hatch build

# 上传 PyPI(需配置 token)
# twine upload dist/*

发布前请确认:

  1. pyproject.tomlauthors、仓库 URL 等信息
  2. 根目录 LICENSE 文件(建议 MIT)
  3. 与服务端约定的 base_url、路径、auth_type 一致

许可证

MIT(请在仓库中附带 LICENSE 文件)。

Changelog

0.1.3

  • auth_type="none":支持无认证模式(不携带 headers/params)
  • factor_path 参数:factor 接口路径可配置(如 /loss),默认仍为 /factor
  • factor 响应字段兼容weather_factor/weather_losscurrent_factor/current_loss 均可解析

0.1.2 (2025-06-27)

  • 类型注解统一from_dict 参数统一为 Mapping[str, Any]
  • 输入校验增强:新增 _safe_parse() 辅助函数,自动过滤非法字段并提供友好错误提示
  • 消除重复 .get() 调用:提取局部变量,提升可读性与性能
  • 补充 docstring:所有 dataclass 及辅助函数均添加文档字符串

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

wr_meteo-0.1.4.tar.gz (10.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

wr_meteo-0.1.4-py3-none-any.whl (9.5 kB view details)

Uploaded Python 3

File details

Details for the file wr_meteo-0.1.4.tar.gz.

File metadata

  • Download URL: wr_meteo-0.1.4.tar.gz
  • Upload date:
  • Size: 10.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.2 {"installer":{"name":"uv","version":"0.11.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for wr_meteo-0.1.4.tar.gz
Algorithm Hash digest
SHA256 ec8d12a43bc3e26eaff6c8ac2ef4126eff22e0a064f5326b7adff2388547d900
MD5 40d916ffc078b964ead6359113aa43d0
BLAKE2b-256 3fe3bc1e9f483f70aa324aad6c42fce374b0337f0ca6c3dfa9f07f74989db583

See more details on using hashes here.

File details

Details for the file wr_meteo-0.1.4-py3-none-any.whl.

File metadata

  • Download URL: wr_meteo-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 9.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.2 {"installer":{"name":"uv","version":"0.11.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for wr_meteo-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 c618b433a69f869ee7021a10284bcd9633dfcce95449c011aac1ea9a8c62d5ef
MD5 6a5e832610e7766b419c3deab3dd516b
BLAKE2b-256 436a5f7c5200ef96d47659a4254c449b6e0ce63d5209e26d579cb525a1cf37e3

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.1.4 This release

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page