-
Notifications
You must be signed in to change notification settings - Fork 0
/
gr_io.py
70 lines (54 loc) · 1.87 KB
/
gr_io.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from pathlib import Path
import requests
def connected_to_internet(url="http://www.google.com/", timeout=5):
"""
Check that there is an internet connection
:param url: url to use for testing (Default value = 'http://www.google.com/')
:param timeout: timeout to wait for [in seconds] (Default value = 5)
"""
try:
_ = requests.get(url, timeout=timeout)
return True
except requests.ConnectionError: # pragma: no cover
print("No internet connection available.") # pragma: no cover
return False
def fail_on_no_connection(func):
"""
Decorator that throws an error if no internet connection is available
"""
if not connected_to_internet(): # pragma: no cover
raise ConnectionError(
"No internet connection found."
) # pragma: no cover
def inner(*args, **kwargs):
return func(*args, **kwargs)
return inner
def request(url):
"""
Sends a request to a url
:param url:
"""
if not connected_to_internet(): # pragma: no cover
raise ConnectionError(
"No internet connection found."
) # pragma: no cover
response = requests.get(url)
if response.ok:
return response
else: # pragma: no cover
exception_string = "URL request failed: {}".format(
response.reason
) # pragma: no cover
raise ValueError(exception_string)
def check_file_exists(func): # pragma: no cover
"""
Decorator that throws an error if a function;s first argument
is not a path to an existing file.
"""
def inner(*args, **kwargs):
if not Path(args[0]).exists():
raise FileNotFoundError(
f"File {args[0]} not found"
) # pragma: no cover
return func(*args, **kwargs)
return inner