1
|
|
|
# Copyright (c) 2020--2022 Stefan Bender |
2
|
|
|
# |
3
|
|
|
# This module is part of pyspaceweather. |
4
|
|
|
# pyspaceweather is free software: you can redistribute it or modify |
5
|
|
|
# it under the terms of the GNU General Public License as published |
6
|
|
|
# by the Free Software Foundation, version 2. |
7
|
|
|
# See accompanying COPYING.GPLv2 file or http://www.gnu.org/licenses/gpl-2.0.html. |
8
|
|
|
"""Python interface for space weather indices |
9
|
|
|
|
10
|
|
|
General file handling functions for space weather data |
11
|
|
|
""" |
12
|
|
|
import errno |
13
|
|
|
import os |
14
|
|
|
import warnings |
15
|
|
|
|
16
|
|
|
import requests |
17
|
|
|
|
18
|
|
|
|
19
|
|
|
def _assert_file_exists(f): |
20
|
|
|
if not os.path.exists(f): |
21
|
|
|
raise IOError(errno.ENOENT, os.strerror(errno.ENOENT), f) |
22
|
|
|
|
23
|
|
|
|
24
|
|
|
def _dl_file(swpath, url): |
25
|
|
|
with requests.get(url, stream=True) as r: |
26
|
|
|
if r.status_code != requests.codes.ok: |
27
|
|
|
if isinstance(r.status_code, int): |
28
|
|
|
warnings.warn( |
29
|
|
|
"Failed to download from {0}, status code: {1}".format( |
30
|
|
|
url, r.status_code, |
31
|
|
|
), |
32
|
|
|
) |
33
|
|
|
return |
34
|
|
|
with open(swpath, 'wb') as fd: |
35
|
|
|
for chunk in r.iter_content(chunk_size=1024): |
36
|
|
|
fd.write(chunk) |
37
|
|
|
|
38
|
|
|
|
39
|
|
|
def _resource_filepath(file, subdir="data"): |
40
|
|
|
try: |
41
|
|
|
from contextlib import ExitStack |
42
|
|
|
from importlib import resources |
43
|
|
|
file_manager = ExitStack() |
44
|
|
|
ref = resources.files(__package__) / subdir / file |
45
|
|
|
filepath = file_manager.enter_context(resources.as_file(ref)) |
46
|
|
|
except (AttributeError, ImportError): |
47
|
|
|
from pkg_resources import resource_filename |
48
|
|
|
filepath = resource_filename(__package__, os.path.join(subdir, file)) |
49
|
|
|
return filepath |
50
|
|
|
|