File size: 1,882 Bytes
378f073 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | """io.py — small shared utilities: id normalization, HTTP, time formatting, logging.
Faithful extraction from the original l3_lib.py (logic unchanged).
"""
import time
import logging
import pandas as pd
import requests
import config
def norm_gage_id(x) -> str:
"""Normalize a USGS site number to 8-digit zero-padded string.
Site numbers longer than 8 digits are preserved at their natural length."""
if pd.isna(x) or str(x).strip() == "":
return ""
s = str(x).strip()
try:
i = int(float(s))
nat = str(i)
return nat.zfill(8) if len(nat) <= 8 else nat
except (ValueError, TypeError):
return s
def safe_float(v, default=None):
try:
return float(v)
except (ValueError, TypeError):
return default
def dt_to_nwis(dt: pd.Timestamp) -> str:
return pd.Timestamp(dt).strftime("%Y-%m-%dT%H:%MZ")
def to_utc(ts: pd.Timestamp) -> pd.Timestamp:
ts = pd.Timestamp(ts)
return ts.tz_localize("UTC") if ts.tzinfo is None else ts.tz_convert("UTC")
def http_get(url, params=None, timeout=20):
"""GET with a fixed inter-call delay; returns Response or None on any error.
In OFFLINE (cache-frozen) mode, suppress the network entirely (returns None),
so cache-miss queries behave as the original run's failure/miss."""
if config.OFFLINE:
return None
try:
time.sleep(config.RATE_DELAY)
r = requests.get(url, params=params, timeout=timeout)
r.raise_for_status()
return r
except Exception:
return None
def get_logger(name="pipeline"):
logger = logging.getLogger(name)
if not logger.handlers:
h = logging.StreamHandler()
h.setFormatter(logging.Formatter("%(asctime)s %(levelname)-7s %(message)s", "%H:%M:%S"))
logger.addHandler(h)
logger.setLevel(logging.INFO)
return logger
|