|
35 | 35 | ) |
36 | 36 | print(f'query URL: {query_url}') |
37 | 37 |
|
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. |
40 | 43 |
|
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() |
43 | 87 |
|
44 | 88 | # Printing resulting dictionary |
45 | 89 | print(results) |
|
48 | 92 | next_url = results['next'] |
49 | 93 | while next_url: |
50 | 94 | # 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 |
52 | 104 | print(next_results) |
53 | 105 |
|
54 | 106 | # Adding to the original results dictionary |
|
0 commit comments