| 1 |
import datetime |
| 2 |
import urllib.request |
| 3 |
from typing import Callable |
| 4 |
|
| 5 |
import mkdocs_get_deps.cache |
| 6 |
|
| 7 |
import mkdocs |
| 8 |
|
| 9 |
|
| 10 |
def download_url(url: str) -> bytes: |
| 11 |
req = urllib.request.Request(url, headers={"User-Agent": f"mkdocs/{mkdocs.__version__}"}) |
| 12 |
with urllib.request.urlopen(req) as resp: |
| 13 |
return resp.read() |
| 14 |
|
| 15 |
|
| 16 |
def download_and_cache_url( |
| 17 |
url: str, |
| 18 |
cache_duration: datetime.timedelta, |
| 19 |
*, |
| 20 |
download: Callable[[str], bytes] = download_url, |
| 21 |
comment: bytes = b"# ", |
| 22 |
) -> bytes: |
| 23 |
""" |
| 24 |
Downloads a file from the URL, stores it under ~/.cache/, and returns its content. |
| 25 |
|
| 26 |
For tracking the age of the content, a prefix is inserted into the stored file, rather than relying on mtime. |
| 27 |
|
| 28 |
Args: |
| 29 |
url: URL to use. |
| 30 |
download: Callback that will accept the URL and actually perform the download. |
| 31 |
cache_duration: How long to consider the URL content cached. |
| 32 |
comment: The appropriate comment prefix for this file format. |
| 33 |
""" |
| 34 |
return mkdocs_get_deps.cache.download_and_cache_url( |
| 35 |
url=url, cache_duration=cache_duration, download=download, comment=comment |
| 36 |
) |