]> git.scottworley.com Git - paperdoorknob/blame - fetch.py
Contemplate generating LaTeX directly
[paperdoorknob] / fetch.py
CommitLineData
705973e7
SW
1# paperdoorknob: Print glowfic
2#
3# This program is free software: you can redistribute it and/or modify it
4# under the terms of the GNU General Public License as published by the
5# Free Software Foundation, version 3.
6
7
8from abc import ABC, abstractmethod
9from contextlib import contextmanager
10from typing import Iterator
11
12import requests
13import requests_cache
14
15
16class Fetcher(ABC):
17 @abstractmethod
18 def fetch(self, url: str) -> bytes:
19 raise NotImplementedError()
20
21
22class _SessionFetcher(Fetcher):
23
24 def __init__(self, session: requests.Session, timeout: int) -> None:
25 self._session = session
26 self._timeout = timeout
27
28 def fetch(self, url: str) -> bytes:
29 with self._session.get(url, timeout=self._timeout) as r:
30 r.raise_for_status()
31 return r.content
32
33
34@contextmanager
35def DirectFetcher(timeout: int) -> Iterator[_SessionFetcher]:
36 with requests.session() as session:
37 yield _SessionFetcher(session, timeout)
38
39
40@contextmanager
41def CachingFetcher(cache_path: str, timeout: int) -> Iterator[_SessionFetcher]:
42 with requests_cache.CachedSession(cache_path, cache_control=True) as session:
43 yield _SessionFetcher(session, timeout)