Skip to content

Commit a08dd9f

Browse files
authored
Merge pull request #13 from TheSpaceDevs/tutorials_launches_past_month_error_handling
LL2, launches past month: exception and http status code handling
2 parents 1ba4cc1 + cbc466d commit a08dd9f

File tree

1 file changed

+57
-5
lines changed

1 file changed

+57
-5
lines changed

tutorials/getting_started_LL2/launches_past_month.py

Lines changed: 57 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,55 @@
3535
)
3636
print(f'query URL: {query_url}')
3737

38-
# Requesting first data
39-
results = requests.get(query_url)
38+
# Function to handle requesting data
39+
def get_results(query_url: str) -> dict or None:
40+
"""
41+
Requests data using
42+
the request GET method.
4043
41-
# Converting to JSON
42-
results = results.json()
44+
Parameters
45+
----------
46+
quer_url : str
47+
URL to query.
48+
49+
Returns
50+
-------
51+
results : dict or None
52+
Results from the query.
53+
54+
Notes
55+
-----
56+
Prints exceptions instead of
57+
raising them as this is script
58+
is only meant as a tutorial.
59+
"""
60+
try:
61+
# Requesting data
62+
results = requests.get(query_url)
63+
except Exception as e:
64+
# Print exception when it occurs
65+
print(f'Exception: {e}')
66+
else:
67+
# Checking status of the query
68+
status = results.status_code
69+
print(f'Status code: {status}')
70+
71+
# Return when the query status isn't 200 OK
72+
# See: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
73+
if status != 200:
74+
return
75+
76+
# Converting to JSON and returning
77+
return results.json()
78+
79+
# Perform first query
80+
results = get_results(query_url)
81+
82+
# Checking if it was succesful
83+
if not results:
84+
# Quitting the program as an example
85+
# use your own error handling here
86+
quit()
4387

4488
# Printing resulting dictionary
4589
print(results)
@@ -48,7 +92,15 @@
4892
next_url = results['next']
4993
while next_url:
5094
# Requesting next data
51-
next_results = requests.get(next_url).json()
95+
next_results = get_results(next_url)
96+
97+
# Checking if it was succesful
98+
if not results:
99+
# Quitting the program as an example
100+
# use your own error handling here
101+
quit()
102+
103+
# Printing next results
52104
print(next_results)
53105

54106
# Adding to the original results dictionary

0 commit comments

Comments
 (0)