From d4d03ebb189bb88d429c64fff1f81f8734723ec4 Mon Sep 17 00:00:00 2001 From: Justin Myers Date: Sat, 20 Apr 2024 14:36:01 -0700 Subject: [PATCH] Use with in examples, remove close in json() --- adafruit_requests.py | 2 +- examples/cpython/requests_cpython_advanced.py | 24 ++++----- .../cpython/requests_cpython_simpletest.py | 48 +++++++---------- .../esp32spi/requests_esp32spi_advanced.py | 21 ++++---- .../esp32spi/requests_esp32spi_simpletest.py | 48 +++++++---------- examples/fona/requests_fona_advanced.py | 21 ++++---- examples/fona/requests_fona_simpletest.py | 48 +++++++---------- ...sts_wifi_adafruit_discord_active_online.py | 4 +- .../expanded/requests_wifi_api_discord.py | 6 ++- .../wifi/expanded/requests_wifi_api_fitbit.py | 15 +++--- .../wifi/expanded/requests_wifi_api_github.py | 9 ++-- .../expanded/requests_wifi_api_mastodon.py | 4 +- ...equests_wifi_api_openskynetwork_private.py | 9 ++-- ...ts_wifi_api_openskynetwork_private_area.py | 9 ++-- ...requests_wifi_api_openskynetwork_public.py | 7 +-- .../requests_wifi_api_premiereleague.py | 6 +-- .../requests_wifi_api_rocketlaunch_live.py | 7 +-- .../wifi/expanded/requests_wifi_api_steam.py | 7 +-- .../wifi/expanded/requests_wifi_api_twitch.py | 23 ++++---- .../expanded/requests_wifi_api_youtube.py | 7 +-- .../requests_wifi_multiple_cookies.py | 54 +++++++++---------- examples/wifi/requests_wifi_advanced.py | 21 ++++---- examples/wifi/requests_wifi_simpletest.py | 32 +++++------ .../wiznet5k/requests_wiznet5k_advanced.py | 21 ++++---- .../wiznet5k/requests_wiznet5k_simpletest.py | 48 +++++++---------- 25 files changed, 213 insertions(+), 288 deletions(-) diff --git a/adafruit_requests.py b/adafruit_requests.py index 9f38502..b6cd54c 100644 --- a/adafruit_requests.py +++ b/adafruit_requests.py @@ -321,7 +321,7 @@ def json(self) -> Any: obj = json_module.load(self._raw) if not self._cached: self._cached = obj - self.close() + return obj def iter_content(self, chunk_size: int = 1, decode_unicode: bool = False) -> bytes: diff --git a/examples/cpython/requests_cpython_advanced.py b/examples/cpython/requests_cpython_advanced.py index 89d715b..b19b37b 100644 --- a/examples/cpython/requests_cpython_advanced.py +++ b/examples/cpython/requests_cpython_advanced.py @@ -15,17 +15,13 @@ headers = {"user-agent": "blinka/1.0.0"} print("Fetching JSON data from %s..." % JSON_GET_URL) -response = requests.get(JSON_GET_URL, headers=headers) -print("-" * 60) - -json_data = response.json() -headers = json_data["headers"] -print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"])) -print("-" * 60) - -# Read Response's HTTP status code -print("Response HTTP Status Code: ", response.status_code) -print("-" * 60) - -# Close, delete and collect the response data -response.close() +with requests.get(JSON_GET_URL, headers=headers) as response: + print("-" * 60) + json_data = response.json() + headers = json_data["headers"] + print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"])) + print("-" * 60) + + # Read Response's HTTP status code + print("Response HTTP Status Code: ", response.status_code) + print("-" * 60) diff --git a/examples/cpython/requests_cpython_simpletest.py b/examples/cpython/requests_cpython_simpletest.py index 70bdfde..a3e10e6 100644 --- a/examples/cpython/requests_cpython_simpletest.py +++ b/examples/cpython/requests_cpython_simpletest.py @@ -14,39 +14,31 @@ JSON_POST_URL = "https://httpbin.org/post" print("Fetching text from %s" % TEXT_URL) -response = requests.get(TEXT_URL) -print("-" * 40) - -print("Text Response: ", response.text) -print("-" * 40) -response.close() +with requests.get(TEXT_URL) as response: + print("-" * 40) + print("Text Response: ", response.text) + print("-" * 40) print("Fetching JSON data from %s" % JSON_GET_URL) -response = requests.get(JSON_GET_URL) -print("-" * 40) - -print("JSON Response: ", response.json()) -print("-" * 40) -response.close() +with requests.get(JSON_GET_URL) as response: + print("-" * 40) + print("JSON Response: ", response.json()) + print("-" * 40) data = "31F" print("POSTing data to {0}: {1}".format(JSON_POST_URL, data)) -response = requests.post(JSON_POST_URL, data=data) -print("-" * 40) - -json_resp = response.json() -# Parse out the 'data' key from json_resp dict. -print("Data received from server:", json_resp["data"]) -print("-" * 40) -response.close() +with requests.post(JSON_POST_URL, data=data) as response: + print("-" * 40) + json_resp = response.json() + # Parse out the 'data' key from json_resp dict. + print("Data received from server:", json_resp["data"]) + print("-" * 40) json_data = {"Date": "July 25, 2019"} print("POSTing data to {0}: {1}".format(JSON_POST_URL, json_data)) -response = requests.post(JSON_POST_URL, json=json_data) -print("-" * 40) - -json_resp = response.json() -# Parse out the 'json' key from json_resp dict. -print("JSON Data received from server:", json_resp["json"]) -print("-" * 40) -response.close() +with requests.post(JSON_POST_URL, json=json_data) as response: + print("-" * 40) + json_resp = response.json() + # Parse out the 'json' key from json_resp dict. + print("JSON Data received from server:", json_resp["json"]) + print("-" * 40) diff --git a/examples/esp32spi/requests_esp32spi_advanced.py b/examples/esp32spi/requests_esp32spi_advanced.py index 66d7b5c..6754dbf 100644 --- a/examples/esp32spi/requests_esp32spi_advanced.py +++ b/examples/esp32spi/requests_esp32spi_advanced.py @@ -53,17 +53,14 @@ headers = {"user-agent": "blinka/1.0.0"} print("Fetching JSON data from %s..." % JSON_GET_URL) -response = requests.get(JSON_GET_URL, headers=headers) -print("-" * 60) +with requests.get(JSON_GET_URL, headers=headers) as response: + print("-" * 60) -json_data = response.json() -headers = json_data["headers"] -print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"])) -print("-" * 60) + json_data = response.json() + headers = json_data["headers"] + print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"])) + print("-" * 60) -# Read Response's HTTP status code -print("Response HTTP Status Code: ", response.status_code) -print("-" * 60) - -# Close, delete and collect the response data -response.close() + # Read Response's HTTP status code + print("Response HTTP Status Code: ", response.status_code) + print("-" * 60) diff --git a/examples/esp32spi/requests_esp32spi_simpletest.py b/examples/esp32spi/requests_esp32spi_simpletest.py index 3ace026..8394df4 100644 --- a/examples/esp32spi/requests_esp32spi_simpletest.py +++ b/examples/esp32spi/requests_esp32spi_simpletest.py @@ -52,39 +52,31 @@ JSON_POST_URL = "https://httpbin.org/post" print("Fetching text from %s" % TEXT_URL) -response = requests.get(TEXT_URL) -print("-" * 40) - -print("Text Response: ", response.text) -print("-" * 40) -response.close() +with requests.get(TEXT_URL) as response: + print("-" * 40) + print("Text Response: ", response.text) + print("-" * 40) print("Fetching JSON data from %s" % JSON_GET_URL) -response = requests.get(JSON_GET_URL) -print("-" * 40) - -print("JSON Response: ", response.json()) -print("-" * 40) -response.close() +with requests.get(JSON_GET_URL) as response: + print("-" * 40) + print("JSON Response: ", response.json()) + print("-" * 40) data = "31F" print("POSTing data to {0}: {1}".format(JSON_POST_URL, data)) -response = requests.post(JSON_POST_URL, data=data) -print("-" * 40) - -json_resp = response.json() -# Parse out the 'data' key from json_resp dict. -print("Data received from server:", json_resp["data"]) -print("-" * 40) -response.close() +with requests.post(JSON_POST_URL, data=data) as response: + print("-" * 40) + json_resp = response.json() + # Parse out the 'data' key from json_resp dict. + print("Data received from server:", json_resp["data"]) + print("-" * 40) json_data = {"Date": "July 25, 2019"} print("POSTing data to {0}: {1}".format(JSON_POST_URL, json_data)) -response = requests.post(JSON_POST_URL, json=json_data) -print("-" * 40) - -json_resp = response.json() -# Parse out the 'json' key from json_resp dict. -print("JSON Data received from server:", json_resp["json"]) -print("-" * 40) -response.close() +with requests.post(JSON_POST_URL, json=json_data) as response: + print("-" * 40) + json_resp = response.json() + # Parse out the 'json' key from json_resp dict. + print("JSON Data received from server:", json_resp["json"]) + print("-" * 40) diff --git a/examples/fona/requests_fona_advanced.py b/examples/fona/requests_fona_advanced.py index 33bc6f0..5af1436 100644 --- a/examples/fona/requests_fona_advanced.py +++ b/examples/fona/requests_fona_advanced.py @@ -54,17 +54,14 @@ headers = {"user-agent": "blinka/1.0.0"} print("Fetching JSON data from %s..." % JSON_GET_URL) -response = requests.get(JSON_GET_URL, headers=headers) -print("-" * 60) +with requests.get(JSON_GET_URL, headers=headers) as response: + print("-" * 60) -json_data = response.json() -headers = json_data["headers"] -print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"])) -print("-" * 60) + json_data = response.json() + headers = json_data["headers"] + print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"])) + print("-" * 60) -# Read Response's HTTP status code -print("Response HTTP Status Code: ", response.status_code) -print("-" * 60) - -# Close, delete and collect the response data -response.close() + # Read Response's HTTP status code + print("Response HTTP Status Code: ", response.status_code) + print("-" * 60) diff --git a/examples/fona/requests_fona_simpletest.py b/examples/fona/requests_fona_simpletest.py index 8841d3d..11ce3a0 100644 --- a/examples/fona/requests_fona_simpletest.py +++ b/examples/fona/requests_fona_simpletest.py @@ -53,39 +53,31 @@ JSON_POST_URL = "http://httpbin.org/post" print("Fetching text from %s" % TEXT_URL) -response = requests.get(TEXT_URL) -print("-" * 40) - -print("Text Response: ", response.text) -print("-" * 40) -response.close() +with requests.get(TEXT_URL) as response: + print("-" * 40) + print("Text Response: ", response.text) + print("-" * 40) print("Fetching JSON data from %s" % JSON_GET_URL) -response = requests.get(JSON_GET_URL) -print("-" * 40) - -print("JSON Response: ", response.json()) -print("-" * 40) -response.close() +with requests.get(JSON_GET_URL) as response: + print("-" * 40) + print("JSON Response: ", response.json()) + print("-" * 40) data = "31F" print("POSTing data to {0}: {1}".format(JSON_POST_URL, data)) -response = requests.post(JSON_POST_URL, data=data) -print("-" * 40) - -json_resp = response.json() -# Parse out the 'data' key from json_resp dict. -print("Data received from server:", json_resp["data"]) -print("-" * 40) -response.close() +with requests.post(JSON_POST_URL, data=data) as response: + print("-" * 40) + json_resp = response.json() + # Parse out the 'data' key from json_resp dict. + print("Data received from server:", json_resp["data"]) + print("-" * 40) json_data = {"Date": "July 25, 2019"} print("POSTing data to {0}: {1}".format(JSON_POST_URL, json_data)) -response = requests.post(JSON_POST_URL, json=json_data) -print("-" * 40) - -json_resp = response.json() -# Parse out the 'json' key from json_resp dict. -print("JSON Data received from server:", json_resp["json"]) -print("-" * 40) -response.close() +with requests.post(JSON_POST_URL, json=json_data) as response: + print("-" * 40) + json_resp = response.json() + # Parse out the 'json' key from json_resp dict. + print("JSON Data received from server:", json_resp["json"]) + print("-" * 40) diff --git a/examples/wifi/expanded/requests_wifi_adafruit_discord_active_online.py b/examples/wifi/expanded/requests_wifi_adafruit_discord_active_online.py index 3ebcaf4..8f6917c 100644 --- a/examples/wifi/expanded/requests_wifi_adafruit_discord_active_online.py +++ b/examples/wifi/expanded/requests_wifi_adafruit_discord_active_online.py @@ -60,8 +60,8 @@ def time_calc(input_time): DEBUG_RESPONSE = True try: - shieldsio_response = requests.get(url=ADA_DISCORD_JSON) - shieldsio_json = shieldsio_response.json() + with requests.get(url=ADA_DISCORD_JSON) as shieldsio_response: + shieldsio_json = shieldsio_response.json() except ConnectionError as e: print(f"Connection Error: {e}") print("Retrying in 10 seconds") diff --git a/examples/wifi/expanded/requests_wifi_api_discord.py b/examples/wifi/expanded/requests_wifi_api_discord.py index 08ad16c..19c2522 100644 --- a/examples/wifi/expanded/requests_wifi_api_discord.py +++ b/examples/wifi/expanded/requests_wifi_api_discord.py @@ -69,8 +69,10 @@ def time_calc(input_time): DEBUG_RESPONSE = False try: - discord_response = requests.get(url=DISCORD_SOURCE, headers=DISCORD_HEADER) - discord_json = discord_response.json() + with requests.get( + url=DISCORD_SOURCE, headers=DISCORD_HEADER + ) as discord_response: + discord_json = discord_response.json() except ConnectionError as e: print(f"Connection Error: {e}") print("Retrying in 10 seconds") diff --git a/examples/wifi/expanded/requests_wifi_api_fitbit.py b/examples/wifi/expanded/requests_wifi_api_fitbit.py index 206a56d..35f3ce2 100644 --- a/examples/wifi/expanded/requests_wifi_api_fitbit.py +++ b/examples/wifi/expanded/requests_wifi_api_fitbit.py @@ -174,17 +174,16 @@ def time_calc(input_time): print(f"Current Refresh Token: {Refresh_Token}") # TOKEN REFRESH POST try: - fitbit_oauth_refresh_POST = requests.post( + with requests.post( url=FITBIT_OAUTH_TOKEN, data=FITBIT_OAUTH_REFRESH_TOKEN, headers=FITBIT_OAUTH_HEADER, - ) + ) as fitbit_oauth_refresh_POST: + fitbit_refresh_oauth_json = fitbit_oauth_refresh_POST.json() except adafruit_requests.OutOfRetries as ex: print(f"OutOfRetries: {ex}") break try: - fitbit_refresh_oauth_json = fitbit_oauth_refresh_POST.json() - fitbit_new_token = fitbit_refresh_oauth_json["access_token"] if DEBUG: print("Your Private SHA-256 Token: ", fitbit_new_token) @@ -252,9 +251,9 @@ def time_calc(input_time): print(" | Attempting to GET Fitbit JSON!") FBIS = FITBIT_INTRADAY_SOURCE FBH = fitbit_header - fitbit_get_response = requests.get(url=FBIS, headers=FBH) try: - fitbit_json = fitbit_get_response.json() + with requests.get(url=FBIS, headers=FBH) as fitbit_get_response: + fitbit_json = fitbit_get_response.json() except ConnectionError as e: print("Connection Error:", e) print("Retrying in 10 seconds") @@ -318,9 +317,9 @@ def time_calc(input_time): print(" | Attempting to GET Device JSON!") FBDS = FITBIT_DEVICE_SOURCE FBH = fitbit_header - fitbit_get_device_response = requests.get(url=FBDS, headers=FBH) try: - fitbit_device_json = fitbit_get_device_response.json() + with requests.get(url=FBDS, headers=FBH) as fitbit_get_device_response: + fitbit_device_json = fitbit_get_device_response.json() except ConnectionError as e: print("Connection Error:", e) print("Retrying in 10 seconds") diff --git a/examples/wifi/expanded/requests_wifi_api_github.py b/examples/wifi/expanded/requests_wifi_api_github.py index ed8aaae..d25b15d 100644 --- a/examples/wifi/expanded/requests_wifi_api_github.py +++ b/examples/wifi/expanded/requests_wifi_api_github.py @@ -61,8 +61,10 @@ def time_calc(input_time): try: print(" | Attempting to GET Github JSON!") try: - github_response = requests.get(url=GITHUB_SOURCE, headers=GITHUB_HEADER) - github_json = github_response.json() + with requests.get( + url=GITHUB_SOURCE, headers=GITHUB_HEADER + ) as github_response: + github_json = github_response.json() except ConnectionError as e: print("Connection Error:", e) print("Retrying in 10 seconds") @@ -92,9 +94,6 @@ def time_calc(input_time): print("Full API GET URL: ", GITHUB_SOURCE) print(github_json) - github_response.close() - print("✂️ Disconnected from Github API") - print("\nFinished!") print(f"Board Uptime: {time_calc(time.monotonic())}") print(f"Next Update: {time_calc(SLEEP_TIME)}") diff --git a/examples/wifi/expanded/requests_wifi_api_mastodon.py b/examples/wifi/expanded/requests_wifi_api_mastodon.py index fd4266e..92455e2 100644 --- a/examples/wifi/expanded/requests_wifi_api_mastodon.py +++ b/examples/wifi/expanded/requests_wifi_api_mastodon.py @@ -75,8 +75,8 @@ def time_calc(input_time): DEBUG_RESPONSE = False try: - mastodon_response = requests.get(url=MAST_SOURCE) - mastodon_json = mastodon_response.json() + with requests.get(url=MAST_SOURCE) as mastodon_response: + mastodon_json = mastodon_response.json() except ConnectionError as e: print(f"Connection Error: {e}") print("Retrying in 10 seconds") diff --git a/examples/wifi/expanded/requests_wifi_api_openskynetwork_private.py b/examples/wifi/expanded/requests_wifi_api_openskynetwork_private.py index 1e340f7..0f024bf 100644 --- a/examples/wifi/expanded/requests_wifi_api_openskynetwork_private.py +++ b/examples/wifi/expanded/requests_wifi_api_openskynetwork_private.py @@ -94,8 +94,10 @@ def _format_datetime(datetime): print(" | Attempting to GET OpenSky-Network Single Private Flight JSON!") print(" | Website Credentials Required! Allows more daily calls than Public.") try: - opensky_response = requests.get(url=OPENSKY_SOURCE, headers=OPENSKY_HEADER) - opensky_json = opensky_response.json() + with requests.get( + url=OPENSKY_SOURCE, headers=OPENSKY_HEADER + ) as opensky_response: + opensky_json = opensky_response.json() except ConnectionError as e: print("Connection Error:", e) print("Retrying in 10 seconds") @@ -178,9 +180,6 @@ def _format_datetime(datetime): else: print(" | | ❌ Flight has no active data or you're polling too fast.") - opensky_response.close() - print("✂️ Disconnected from OpenSky-Network API") - print("\nFinished!") print(f"Board Uptime: {time_calc(time.monotonic())}") print(f"Next Update: {time_calc(SLEEP_TIME)}") diff --git a/examples/wifi/expanded/requests_wifi_api_openskynetwork_private_area.py b/examples/wifi/expanded/requests_wifi_api_openskynetwork_private_area.py index 1652a73..322115f 100644 --- a/examples/wifi/expanded/requests_wifi_api_openskynetwork_private_area.py +++ b/examples/wifi/expanded/requests_wifi_api_openskynetwork_private_area.py @@ -108,8 +108,10 @@ def _format_datetime(datetime): try: print(" | Attempting to GET OpenSky-Network Area Flights JSON!") try: - opensky_response = requests.get(url=OPENSKY_SOURCE, headers=OSN_HEADER) - opensky_json = opensky_response.json() + with requests.get( + url=OPENSKY_SOURCE, headers=OSN_HEADER + ) as opensky_response: + opensky_json = opensky_response.json() except ConnectionError as e: print("Connection Error:", e) print("Retrying in 10 seconds") @@ -184,9 +186,6 @@ def _format_datetime(datetime): else: print(" | | ❌ Area has no active data or you're polling too fast.") - opensky_response.close() - print("✂️ Disconnected from OpenSky-Network API") - print("\nFinished!") print(f"Board Uptime: {time_calc(time.monotonic())}") print(f"Next Update: {time_calc(SLEEP_TIME)}") diff --git a/examples/wifi/expanded/requests_wifi_api_openskynetwork_public.py b/examples/wifi/expanded/requests_wifi_api_openskynetwork_public.py index 9151343..a2eb873 100644 --- a/examples/wifi/expanded/requests_wifi_api_openskynetwork_public.py +++ b/examples/wifi/expanded/requests_wifi_api_openskynetwork_public.py @@ -80,8 +80,8 @@ def _format_datetime(datetime): print(" | Attempting to GET OpenSky-Network Single Public Flight JSON!") print(" | Website Credentials NOT Required! Less daily calls than Private.") try: - opensky_response = requests.get(url=OPENSKY_SOURCE) - opensky_json = opensky_response.json() + with requests.get(url=OPENSKY_SOURCE) as opensky_response: + opensky_json = opensky_response.json() except ConnectionError as e: print("Connection Error:", e) print("Retrying in 10 seconds") @@ -163,9 +163,6 @@ def _format_datetime(datetime): print("This flight has no active data or you're polling too fast.") print("Public Limits: 10 second max poll & 400 weighted calls daily") - opensky_response.close() - print("✂️ Disconnected from OpenSky-Network API") - print("\nFinished!") print(f"Board Uptime: {time_calc(time.monotonic())}") print(f"Next Update: {time_calc(SLEEP_TIME)}") diff --git a/examples/wifi/expanded/requests_wifi_api_premiereleague.py b/examples/wifi/expanded/requests_wifi_api_premiereleague.py index 88524e9..5f61e1a 100644 --- a/examples/wifi/expanded/requests_wifi_api_premiereleague.py +++ b/examples/wifi/expanded/requests_wifi_api_premiereleague.py @@ -62,16 +62,14 @@ def time_calc(input_time): DEBUG_RESPONSE = False try: - PREMIERE_LEAGUE_RESPONSE = requests.get(url=PREMIERE_LEAGUE_SOURCE) - pl_json = json_stream.load(PREMIERE_LEAGUE_RESPONSE.iter_content(32)) + with requests.get(url=PREMIERE_LEAGUE_SOURCE) as PREMIERE_LEAGUE_RESPONSE: + pl_json = json_stream.load(PREMIERE_LEAGUE_RESPONSE.iter_content(32)) except ConnectionError as e: print(f"Connection Error: {e}") print("Retrying in 10 seconds") print(" | ✅ Premiere League JSON!") print(f" | Total Premiere League Players: {pl_json['total_players']}") - PREMIERE_LEAGUE_RESPONSE.close() - print("✂️ Disconnected from Premiere League") print("\nFinished!") print(f"Board Uptime: {time.monotonic()}") diff --git a/examples/wifi/expanded/requests_wifi_api_rocketlaunch_live.py b/examples/wifi/expanded/requests_wifi_api_rocketlaunch_live.py index 7cf9d61..67034bb 100644 --- a/examples/wifi/expanded/requests_wifi_api_rocketlaunch_live.py +++ b/examples/wifi/expanded/requests_wifi_api_rocketlaunch_live.py @@ -58,8 +58,8 @@ def time_calc(input_time): debug_rocketlaunch_full_response = False try: - rocketlaunch_response = requests.get(url=ROCKETLAUNCH_SOURCE) - rocketlaunch_json = rocketlaunch_response.json() + with requests.get(url=ROCKETLAUNCH_SOURCE) as rocketlaunch_response: + rocketlaunch_json = rocketlaunch_response.json() except ConnectionError as e: print("Connection Error:", e) print("Retrying in 10 seconds") @@ -120,9 +120,6 @@ def time_calc(input_time): if RLM != "None": print(f" | | Mission: {RLM}") - rocketlaunch_response.close() - print("✂️ Disconnected from RocketLaunch.Live API") - print("\nFinished!") print(f"Board Uptime: {time_calc(time.monotonic())}") print(f"Next Update: {time_calc(SLEEP_TIME)}") diff --git a/examples/wifi/expanded/requests_wifi_api_steam.py b/examples/wifi/expanded/requests_wifi_api_steam.py index fb1f7bd..42d1e31 100644 --- a/examples/wifi/expanded/requests_wifi_api_steam.py +++ b/examples/wifi/expanded/requests_wifi_api_steam.py @@ -89,8 +89,8 @@ def _format_datetime(datetime): try: print(" | Attempting to GET Steam API JSON!") try: - steam_response = requests.get(url=STEAM_SOURCE) - steam_json = steam_response.json() + with requests.get(url=STEAM_SOURCE) as steam_response: + steam_json = steam_response.json() except ConnectionError as e: print("Connection Error:", e) print("Retrying in 10 seconds") @@ -114,9 +114,6 @@ def _format_datetime(datetime): print(f" | | Total Days: {total_days}") print(f" | | Total Years: {total_years:.2f}") - steam_response.close() - print("✂️ Disconnected from Steam API") - print("\nFinished!") print(f"Board Uptime: {time_calc(time.monotonic())}") print(f"Next Update: {time_calc(SLEEP_TIME)}") diff --git a/examples/wifi/expanded/requests_wifi_api_twitch.py b/examples/wifi/expanded/requests_wifi_api_twitch.py index 1f02e5c..57f9cdd 100644 --- a/examples/wifi/expanded/requests_wifi_api_twitch.py +++ b/examples/wifi/expanded/requests_wifi_api_twitch.py @@ -94,12 +94,14 @@ def _format_datetime(datetime): ) # POST REQUEST - twitch_0auth_response = requests.post( - url=TWITCH_0AUTH_TOKEN, data=twitch_0auth_data, headers=twitch_0auth_header - ) try: - twitch_0auth_json = twitch_0auth_response.json() - twitch_access_token = twitch_0auth_json["access_token"] + with requests.post( + url=TWITCH_0AUTH_TOKEN, + data=twitch_0auth_data, + headers=twitch_0auth_header, + ) as twitch_0auth_response: + twitch_0auth_json = twitch_0auth_response.json() + twitch_access_token = twitch_0auth_json["access_token"] except ConnectionError as e: print(f"Connection Error: {e}") print("Retrying in 10 seconds") @@ -133,11 +135,11 @@ def _format_datetime(datetime): + TWITCH_UID ) print(" | Attempting to GET Twitch JSON!") - twitch_response = requests.get( - url=TWITCH_FOLLOWERS_SOURCE, headers=twitch_header - ) try: - twitch_json = twitch_response.json() + with requests.get( + url=TWITCH_FOLLOWERS_SOURCE, headers=twitch_header + ) as twitch_response: + twitch_json = twitch_response.json() except ConnectionError as e: print(f"Connection Error: {e}") print("Retrying in 10 seconds") @@ -164,9 +166,6 @@ def _format_datetime(datetime): twitch_followers = twitch_json["total"] print(f" | | Followers: {twitch_followers}") - twitch_response.close() - print("✂️ Disconnected from Twitch API") - print("\nFinished!") print(f"Board Uptime: {time_calc(time.monotonic())}") print(f"Next Update: {time_calc(SLEEP_TIME)}") diff --git a/examples/wifi/expanded/requests_wifi_api_youtube.py b/examples/wifi/expanded/requests_wifi_api_youtube.py index c69c146..a616d99 100644 --- a/examples/wifi/expanded/requests_wifi_api_youtube.py +++ b/examples/wifi/expanded/requests_wifi_api_youtube.py @@ -69,8 +69,8 @@ def time_calc(input_time): try: print(" | Attempting to GET YouTube JSON...") try: - youtube_response = requests.get(url=YOUTUBE_SOURCE) - youtube_json = youtube_response.json() + with requests.get(url=YOUTUBE_SOURCE) as youtube_response: + youtube_json = youtube_response.json() except ConnectionError as e: print("Connection Error:", e) print("Retrying in 10 seconds") @@ -105,9 +105,6 @@ def time_calc(input_time): YT_response_kind = youtube_json["kind"] print(f" | | Response Kind: {YT_response_kind}") - youtube_response.close() - print("✂️ Disconnected from YouTube API") - print("\nFinished!") print(f"Board Uptime: {time_calc(time.monotonic())}") print(f"Next Update: {time_calc(SLEEP_TIME)}") diff --git a/examples/wifi/expanded/requests_wifi_multiple_cookies.py b/examples/wifi/expanded/requests_wifi_multiple_cookies.py index 9237903..cfc0641 100644 --- a/examples/wifi/expanded/requests_wifi_multiple_cookies.py +++ b/examples/wifi/expanded/requests_wifi_multiple_cookies.py @@ -25,38 +25,36 @@ try: # Connect to the Wi-Fi network wifi.radio.connect(ssid, password) - # URL GET Request - response = requests.get(COOKIE_TEST_URL) except OSError as e: print(f"❌ OSError: {e}") print("✅ Wifi!") -print(f" | Fetching Cookies: {COOKIE_TEST_URL}") - -# Spilt up the cookies by ", " -elements = response.headers["set-cookie"].split(", ") - -# NOTE: Some cookies use ", " when describing dates. This code will iterate through -# the previously split up 'set-cookie' header value and piece back together cookies -# that were accidentally split up for this reason -days_of_week = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") -elements_iter = iter(elements) -cookie_list = [] -for element in elements_iter: - captured_day = [day for day in days_of_week if element.endswith(day)] - if captured_day: - cookie_list.append(element + ", " + next(elements_iter)) - else: - cookie_list.append(element) - -# Pring the information about the cookies -print(f" | Total Cookies: {len(cookie_list)}") -print("-" * 80) - -for cookie in cookie_list: - print(f" | 🍪 {cookie}") +# URL GET Request +with requests.get(COOKIE_TEST_URL) as response: + print(f" | Fetching Cookies: {COOKIE_TEST_URL}") + + # Spilt up the cookies by ", " + elements = response.headers["set-cookie"].split(", ") + + # NOTE: Some cookies use ", " when describing dates. This code will iterate through + # the previously split up 'set-cookie' header value and piece back together cookies + # that were accidentally split up for this reason + days_of_week = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") + elements_iter = iter(elements) + cookie_list = [] + for element in elements_iter: + captured_day = [day for day in days_of_week if element.endswith(day)] + if captured_day: + cookie_list.append(element + ", " + next(elements_iter)) + else: + cookie_list.append(element) + + # Pring the information about the cookies + print(f" | Total Cookies: {len(cookie_list)}") print("-" * 80) -response.close() -print(f"✂️ Disconnected from {COOKIE_TEST_URL}") + for cookie in cookie_list: + print(f" | 🍪 {cookie}") + print("-" * 80) + print("Finished!") diff --git a/examples/wifi/requests_wifi_advanced.py b/examples/wifi/requests_wifi_advanced.py index 3bb0976..7e3c8fc 100644 --- a/examples/wifi/requests_wifi_advanced.py +++ b/examples/wifi/requests_wifi_advanced.py @@ -35,17 +35,14 @@ headers = {"user-agent": "blinka/1.0.0"} print("Fetching JSON data from %s..." % JSON_GET_URL) -response = requests.get(JSON_GET_URL, headers=headers) -print("-" * 60) +with requests.get(JSON_GET_URL, headers=headers) as response: + print("-" * 60) -json_data = response.json() -headers = json_data["headers"] -print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"])) -print("-" * 60) + json_data = response.json() + headers = json_data["headers"] + print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"])) + print("-" * 60) -# Read Response's HTTP status code -print("Response HTTP Status Code: ", response.status_code) -print("-" * 60) - -# Close, delete and collect the response data -response.close() + # Read Response's HTTP status code + print("Response HTTP Status Code: ", response.status_code) + print("-" * 60) diff --git a/examples/wifi/requests_wifi_simpletest.py b/examples/wifi/requests_wifi_simpletest.py index 21492fb..6bce412 100644 --- a/examples/wifi/requests_wifi_simpletest.py +++ b/examples/wifi/requests_wifi_simpletest.py @@ -34,37 +34,29 @@ print("✅ Wifi!") print(f" | GET Text Test: {TEXT_URL}") -response = requests.get(TEXT_URL) -print(f" | ✅ GET Response: {response.text}") -response.close() -print(f" | ✂️ Disconnected from {TEXT_URL}") +with requests.get(TEXT_URL) as response: + print(f" | ✅ GET Response: {response.text}") print("-" * 80) print(f" | GET Full Response Test: {JSON_GET_URL}") -response = requests.get(JSON_GET_URL) -print(f" | ✅ Unparsed Full JSON Response: {response.json()}") -response.close() -print(f" | ✂️ Disconnected from {JSON_GET_URL}") +with requests.get(JSON_GET_URL) as response: + print(f" | ✅ Unparsed Full JSON Response: {response.json()}") print("-" * 80) DATA = "This is an example of a JSON value" print(f" | ✅ JSON 'value' POST Test: {JSON_POST_URL} {DATA}") -response = requests.post(JSON_POST_URL, data=DATA) -json_resp = response.json() -# Parse out the 'data' key from json_resp dict. -print(f" | ✅ JSON 'value' Response: {json_resp['data']}") -response.close() -print(f" | ✂️ Disconnected from {JSON_POST_URL}") +with requests.post(JSON_POST_URL, data=DATA) as response: + json_resp = response.json() + # Parse out the 'data' key from json_resp dict. + print(f" | ✅ JSON 'value' Response: {json_resp['data']}") print("-" * 80) json_data = {"Date": "January 1, 1970"} print(f" | ✅ JSON 'key':'value' POST Test: {JSON_POST_URL} {json_data}") -response = requests.post(JSON_POST_URL, json=json_data) -json_resp = response.json() -# Parse out the 'json' key from json_resp dict. -print(f" | ✅ JSON 'key':'value' Response: {json_resp['json']}") -response.close() -print(f" | ✂️ Disconnected from {JSON_POST_URL}") +with requests.post(JSON_POST_URL, json=json_data) as response: + json_resp = response.json() + # Parse out the 'json' key from json_resp dict. + print(f" | ✅ JSON 'key':'value' Response: {json_resp['json']}") print("-" * 80) print("Finished!") diff --git a/examples/wiznet5k/requests_wiznet5k_advanced.py b/examples/wiznet5k/requests_wiznet5k_advanced.py index e98e728..1f068ee 100644 --- a/examples/wiznet5k/requests_wiznet5k_advanced.py +++ b/examples/wiznet5k/requests_wiznet5k_advanced.py @@ -26,17 +26,14 @@ headers = {"user-agent": "blinka/1.0.0"} print("Fetching JSON data from %s..." % JSON_GET_URL) -response = requests.get(JSON_GET_URL, headers=headers) -print("-" * 60) +with requests.get(JSON_GET_URL, headers=headers) as response: + print("-" * 60) -json_data = response.json() -headers = json_data["headers"] -print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"])) -print("-" * 60) + json_data = response.json() + headers = json_data["headers"] + print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"])) + print("-" * 60) -# Read Response's HTTP status code -print("Response HTTP Status Code: ", response.status_code) -print("-" * 60) - -# Close, delete and collect the response data -response.close() + # Read Response's HTTP status code + print("Response HTTP Status Code: ", response.status_code) + print("-" * 60) diff --git a/examples/wiznet5k/requests_wiznet5k_simpletest.py b/examples/wiznet5k/requests_wiznet5k_simpletest.py index e35b5ab..74e060b 100644 --- a/examples/wiznet5k/requests_wiznet5k_simpletest.py +++ b/examples/wiznet5k/requests_wiznet5k_simpletest.py @@ -25,39 +25,31 @@ JSON_POST_URL = "http://httpbin.org/post" print("Fetching text from %s" % TEXT_URL) -response = requests.get(TEXT_URL) -print("-" * 40) - -print("Text Response: ", response.text) -print("-" * 40) -response.close() +with requests.get(TEXT_URL) as response: + print("-" * 40) + print("Text Response: ", response.text) + print("-" * 40) print("Fetching JSON data from %s" % JSON_GET_URL) -response = requests.get(JSON_GET_URL) -print("-" * 40) - -print("JSON Response: ", response.json()) -print("-" * 40) -response.close() +with requests.get(JSON_GET_URL) as response: + print("-" * 40) + print("JSON Response: ", response.json()) + print("-" * 40) data = "31F" print("POSTing data to {0}: {1}".format(JSON_POST_URL, data)) -response = requests.post(JSON_POST_URL, data=data) -print("-" * 40) - -json_resp = response.json() -# Parse out the 'data' key from json_resp dict. -print("Data received from server:", json_resp["data"]) -print("-" * 40) -response.close() +with requests.post(JSON_POST_URL, data=data) as response: + print("-" * 40) + json_resp = response.json() + # Parse out the 'data' key from json_resp dict. + print("Data received from server:", json_resp["data"]) + print("-" * 40) json_data = {"Date": "July 25, 2019"} print("POSTing data to {0}: {1}".format(JSON_POST_URL, json_data)) -response = requests.post(JSON_POST_URL, json=json_data) -print("-" * 40) - -json_resp = response.json() -# Parse out the 'json' key from json_resp dict. -print("JSON Data received from server:", json_resp["json"]) -print("-" * 40) -response.close() +with requests.post(JSON_POST_URL, json=json_data) as response: + print("-" * 40) + json_resp = response.json() + # Parse out the 'json' key from json_resp dict. + print("JSON Data received from server:", json_resp["json"]) + print("-" * 40)