Fall back to OMDb demo on rate limits

This commit is contained in:
SirBlob committed 2026-11-01 22:58:56 -05:00
1 parent 4f78883f0b
commit dfe3955604
2 files changed
+28 -5

No files matched your search

+15 -3
View File
@@ -1,6 +1,7 @@
import json
import os
import re
import urllib.error
import urllib.parse
import urllib.request
@@ -8,6 +9,9 @@ from jsonfile import PROJECT_ROOT
IMDB_ID_PATTERN = re.compile(r"tt\d{7,9}")
ENV_FILE = PROJECT_ROOT / ".env"
OMDB_URL = "https://www.omdbapi.com/"
OMDB_DEMO_URL = "http://www.omdbapi.com/demo.aspx/"
RATE_LIMITED_STATUS = 401
def imdb_id(text: str) -> str | None:
@@ -31,14 +35,22 @@ def omdb_api_key() -> str | None:
return None
def request_json(url: str, parameters: dict) -> dict:
with urllib.request.urlopen(f"{url}?{urllib.parse.urlencode(parameters)}", timeout=10) as response:
return json.load(response)
def lookup(identifier: str) -> dict | None:
api_key = omdb_api_key()
if not api_key:
return None
query = urllib.parse.urlencode({"apikey": api_key, "i": identifier})
try:
with urllib.request.urlopen(f"https://www.omdbapi.com/?{query}", timeout=10) as response:
result = json.load(response)
try:
result = request_json(OMDB_URL, {"apikey": api_key, "i": identifier})
except urllib.error.HTTPError as error:
if error.code != RATE_LIMITED_STATUS:
raise
result = request_json(OMDB_DEMO_URL, {"i": identifier, "token": "demo"})
except (OSError, ValueError):
return None
return result if result.get("Response") == "True" else None