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
  • Query:lon, lat, ts(Unix 时间戳,秒)
  • 返回:PointMeteo

get_meteo_factor / get_meteo_factor_async

  • 路径:{base_url}{factor_path},默认 /factor,可配置
  • Query:imo, 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 约定(摘要)

/point → PointMeteo 字段与 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,缺失时为 None(MarineMeteo 内 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.toml 中 authors、仓库 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_loss、current_factor/current_loss 均可解析

0.1.2 (2025-06-27)

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

Metadata

Release files for wr-meteo 0.1.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for wr-meteo 0.1.6
File Size Uploaded Provenance Actions
wr_meteo-0.1.6.tar.gz 10.9 kB Without provenance Details for wr_meteo-0.1.6.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for wr-meteo 0.1.6
File Interpreter ABI Platform Actions
wr_meteo-0.1.6-py3-none-any.whl Python 3 none any Details for wr_meteo-0.1.6-py3-none-any.whl

Total release size: 20.6 kB

Release files / wr_meteo-0.1.6.tar.gz

Download URL wr_meteo-0.1.6.tar.gz
Size 10.9 kB
Tags Source
SHA-256 checksum
How to use checksums
a8c64044223162eb0ff4749320f2cc481c8f3ef312364a3209b660195eee4909
BLAKE2b-256 checksum
How to use checksums
428fb98998d2dcf8e0529df3dc52302d8930b58b1802a9caa8910fde99fb8e0a
Upload date
Uploaded using Trusted Publishing?
What is 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}

Release files / wr_meteo-0.1.6-py3-none-any.whl

Download URL wr_meteo-0.1.6-py3-none-any.whl
Size 9.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e945632e271247294488f07c7cb1c5cee12cdd827b409cd24b6dc4a2b066e97b
BLAKE2b-256 checksum
How to use checksums
888c6b1a22b9ae3ce53fef9ae9478c5ca26900656347e7b901fdbe6431aaaf78
Upload date
Uploaded using Trusted Publishing?
What is 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}

Security for wr-meteo 0.1.6

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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