|
| 1 | +import os |
| 2 | +from shutil import rmtree |
| 3 | + |
1 | 4 | try:
|
2 | 5 | import requests
|
3 | 6 | from platformdirs import user_cache_path
|
4 | 7 | except ImportError:
|
5 |
| - raise ImportError("requests and platformdirs are needed to download data") |
| 8 | + raise ImportError("requests and platformdirs are needed to download data") from None |
| 9 | + |
| 10 | + |
| 11 | +if os.environ.get("GITHUB_TOKEN"): |
| 12 | + HEADERS = {"Authorization": f"token {os.environ['GITHUB_TOKEN']}"} |
| 13 | +else: |
| 14 | + HEADERS = None |
6 | 15 |
|
7 | 16 |
|
8 | 17 | def download_map(dataset):
|
9 | 18 | if dataset not in ("naturalearth_lowres", "naturalearth_cities"):
|
10 |
| - raise ValueError(f"Unknown dataset: {dataset}, supported datasets are 'naturalearth_lowres' and 'naturalearth_cities'") |
| 19 | + raise ValueError( |
| 20 | + f"Unknown dataset: {dataset}, supported datasets are 'naturalearth_lowres' and 'naturalearth_cities'" |
| 21 | + ) |
11 | 22 | url = f"https://api.github.com/repos/geopandas/geopandas/contents/geopandas/datasets/{dataset}?ref=v0.14.4"
|
12 | 23 | local_dir = user_cache_path() / "spatialpandas" / dataset
|
13 | 24 |
|
14 | 25 | if local_dir.exists():
|
15 | 26 | return local_dir
|
16 | 27 |
|
17 |
| - response = requests.get(url) |
18 |
| - if response.status_code == 200: |
| 28 | + response = requests.get(url, headers=HEADERS) |
| 29 | + if response.ok: |
19 | 30 | files = response.json()
|
20 | 31 | else:
|
21 |
| - print(f"Failed to retrieve contents: {response.status_code}") |
22 |
| - return None |
| 32 | + raise ValueError( |
| 33 | + f"Failed to retrieve contents ({response.status_code}): \n {response.text}" |
| 34 | + ) |
23 | 35 |
|
24 | 36 | if not local_dir.exists():
|
25 | 37 | local_dir.mkdir(parents=True)
|
26 | 38 |
|
27 | 39 | for file in files:
|
28 | 40 | file_url = file["download_url"]
|
29 | 41 | file_name = file["name"]
|
30 |
| - file_response = requests.get(file_url) |
| 42 | + file_response = requests.get(file_url, headers=HEADERS) |
| 43 | + if not file_response.ok: |
| 44 | + rmtree(local_dir) |
| 45 | + raise ValueError(f"Failed to download file: {file_name}, \n{file_response.text}") |
31 | 46 | with open(local_dir / file_name, "wb") as f:
|
32 | 47 | f.write(file_response.content)
|
33 | 48 |
|
34 | 49 | return local_dir
|
| 50 | + |
| 51 | + |
| 52 | +if __name__ == "__main__": |
| 53 | + download_map("naturalearth_lowres") |
| 54 | + download_map("naturalearth_cities") |
0 commit comments