From 98ced2fbec2579f70404a012116a1ef334359701 Mon Sep 17 00:00:00 2001 From: TehPeGaSuS <25697531+TehPeGaSuS@users.noreply.github.com> Date: Tue, 5 May 2026 15:22:40 +0200 Subject: [PATCH] Refactor shorten method and from_config function Refactor payload and headers creation for clarity. Simplify the from_config function by combining multiple lines into single lines. --- shlink.py | 36 +++++++----------------------------- 1 file changed, 7 insertions(+), 29 deletions(-) diff --git a/shlink.py b/shlink.py index f017bd5..c5ff349 100644 --- a/shlink.py +++ b/shlink.py @@ -23,45 +23,23 @@ class ShlinkClient: async def shorten(self, url: str) -> str: """Return a shortened URL, or ``url`` unchanged on failure.""" - payload = { - "longUrl": url, - "findIfExists": True # Prevents creating duplicate slugs for the same URL - } + payload = {"longUrl": url, "findIfExists": True} if self._domain: payload["domain"] = self._domain - headers = { - "X-Api-Key": self._api_key, - "Content-Type": "application/json", - } + headers = {"X-Api-Key": self._api_key, "Content-Type": "application/json"} try: - # Using a context manager ensures the connection is closed immediately async with httpx.AsyncClient(timeout=self._timeout) as client: resp = await client.post(self._endpoint, json=payload, headers=headers) resp.raise_for_status() - data = resp.json() - - short = data["shortUrl"] - log.debug("Shortened %s → %s", url, short) - return short + return resp.json()["shortUrl"] except Exception as e: log.warning("Shlink error for %s: %s", url, e) return url def from_config(cfg: dict) -> "ShlinkClient | None": - """Build a ShlinkClient from the [shlink] config section.""" - if not cfg.get("enabled", True): - return None - base = cfg.get("url", "").strip() - api_key = cfg.get("api_key", "").strip() - if not base or not api_key: - if base or api_key: - log.warning("[shlink] Both 'url' and 'api_key' are required — disabling") - return None - return ShlinkClient( - base_url=base, - api_key=api_key, - timeout=int(cfg.get("timeout", 5)), - domain=cfg.get("domain") or None, - ) \ No newline at end of file + if not cfg.get("enabled", True): return None + base, api_key = cfg.get("url", "").strip(), cfg.get("api_key", "").strip() + if not base or not api_key: return None + return ShlinkClient(base, api_key, int(cfg.get("timeout", 5)), cfg.get("domain"))