From 211c2d882ffaf0af94dafe6c0e6a60cae1f2b5b7 Mon Sep 17 00:00:00 2001 From: DJDevon3 <49322231+DJDevon3@users.noreply.github.com> Date: Mon, 25 Mar 2024 05:17:06 -0400 Subject: [PATCH 01/13] update requests_wifi_advanced to 9.0 with Connection Manager --- examples/wifi/requests_wifi_advanced.py | 46 ++++++++++++++----------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/examples/wifi/requests_wifi_advanced.py b/examples/wifi/requests_wifi_advanced.py index 3bb0976..f59d510 100644 --- a/examples/wifi/requests_wifi_advanced.py +++ b/examples/wifi/requests_wifi_advanced.py @@ -1,10 +1,12 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT +# Updated for Circuit Python 9.0 +""" WiFi Advanced Example """ +# pylint: disable=import-error import os -import ssl -import socketpool +import adafruit_connection_manager import wifi import adafruit_requests @@ -13,39 +15,41 @@ ssid = os.getenv("CIRCUITPY_WIFI_SSID") password = os.getenv("CIRCUITPY_WIFI_PASSWORD") -# Initialize WiFi Pool (There can be only 1 pool & top of script) -radio = wifi.radio -pool = socketpool.SocketPool(radio) - -print("Connecting to AP...") -while not wifi.radio.ipv4_address: - try: - wifi.radio.connect(ssid, password) - except ConnectionError as e: - print("could not connect to AP, retrying: ", e) -print("Connected to", str(radio.ap_info.ssid, "utf-8"), "\tRSSI:", radio.ap_info.rssi) +TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html" +JSON_GET_URL = "https://httpbin.org/get" +JSON_POST_URL = "https://httpbin.org/post" -# Initialize a requests session -ssl_context = ssl.create_default_context() +# Initalize Wifi, Socket Pool, Request Session +pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio) +ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio) requests = adafruit_requests.Session(pool, ssl_context) +rssi = wifi.radio.ap_info.rssi + +print(f"\nConnecting to {ssid}...") +print(f"Signal Strength: {rssi}") +try: + # Connect to the Wi-Fi network + wifi.radio.connect(ssid, password) +except OSError as e: + print(f"❌ OSError: {e}") +print("✅ Wifi!") JSON_GET_URL = "https://httpbin.org/get" # Define a custom header as a dict. headers = {"user-agent": "blinka/1.0.0"} -print("Fetching JSON data from %s..." % JSON_GET_URL) +print(f" | Fetching JSON: {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) +print(f" | ✅ Response Custom User-Agent Header: {headers['User-Agent']}") # Read Response's HTTP status code -print("Response HTTP Status Code: ", response.status_code) -print("-" * 60) +print(f" | ✅ Response HTTP Status Code: {response.status_code}") # Close, delete and collect the response data response.close() +print(f" | ✂️ Disconnected from {JSON_GET_URL}") +print("Finished!") From 7c2cb6c293f0e7b6c2162a9ad8cc6b2e52abee89 Mon Sep 17 00:00:00 2001 From: DJDevon3 <49322231+DJDevon3@users.noreply.github.com> Date: Tue, 26 Mar 2024 02:19:03 -0400 Subject: [PATCH 02/13] update with HTTP status code tester httpbin has pages to test all HTTP status codes --- examples/wifi/requests_wifi_advanced.py | 121 +++++++++++++++++++++--- 1 file changed, 109 insertions(+), 12 deletions(-) diff --git a/examples/wifi/requests_wifi_advanced.py b/examples/wifi/requests_wifi_advanced.py index f59d510..00cdf25 100644 --- a/examples/wifi/requests_wifi_advanced.py +++ b/examples/wifi/requests_wifi_advanced.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT # Updated for Circuit Python 9.0 -""" WiFi Advanced Example """ +""" WiFi Advanced (User-Agent & Status Codes) Example """ # pylint: disable=import-error import os @@ -15,9 +15,8 @@ ssid = os.getenv("CIRCUITPY_WIFI_SSID") password = os.getenv("CIRCUITPY_WIFI_PASSWORD") -TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html" JSON_GET_URL = "https://httpbin.org/get" -JSON_POST_URL = "https://httpbin.org/post" +STATUS_TEST = "https://httpbin.org/status/" # Initalize Wifi, Socket Pool, Request Session pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio) @@ -25,6 +24,87 @@ requests = adafruit_requests.Session(pool, ssl_context) rssi = wifi.radio.ap_info.rssi + +def print_http_status(code, description): + """Returns HTTP status code and description""" + if "100" <= code <= "103": + print(f" | ✅ Status Test: {code} - {description}") + elif "200" <= code <= "299": + print(f" | ✅ Status Test: {code} - {description}") + elif "300" <= code <= "600": + print(f" | ❌ Status Test: {code} - {description}") + else: + print(f" | Unknown Response Status: {code} - {description}") + + +# All HTTP Status Codes +http_status_codes = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "Unused", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Too Early", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "510": "Not Extended", + "511": "Network Authentication Required", +} + + print(f"\nConnecting to {ssid}...") print(f"Signal Strength: {rssi}") try: @@ -37,19 +117,36 @@ JSON_GET_URL = "https://httpbin.org/get" # Define a custom header as a dict. -headers = {"user-agent": "blinka/1.0.0"} +HEADERS = {"user-agent": "blinka/1.0.0"} -print(f" | Fetching JSON: {JSON_GET_URL}") -response = requests.get(JSON_GET_URL, headers=headers) +print(f" | GET JSON: {JSON_GET_URL}") +response = requests.get(JSON_GET_URL, headers=HEADERS) json_data = response.json() -headers = json_data["headers"] -print(f" | ✅ Response Custom User-Agent Header: {headers['User-Agent']}") +HEADERS = json_data["headers"] +print(f" | User-Agent: {HEADERS['User-Agent']}") -# Read Response's HTTP status code -print(f" | ✅ Response HTTP Status Code: {response.status_code}") - -# Close, delete and collect the response data +# HTTP STATUS CODE TESTING +# https://developer.mozilla.org/en-US/docs/Web/HTTP/Status +STATUS_CODE = str(response.status_code) +STATUS_DESCRIPTION = http_status_codes.get(STATUS_CODE, "Unknown Status Code") +print_http_status(STATUS_CODE, STATUS_DESCRIPTION) response.close() print(f" | ✂️ Disconnected from {JSON_GET_URL}") +print(" | ") +print(f" | Status Code Test: {JSON_GET_URL}") + +# Some return errors then confirm the error (that's a good thing) +# Demonstrates not all errors have the same behavior +# 300, 304, and 306 in particular +for codes in sorted(http_status_codes.keys(), key=int): + status_test_url = STATUS_TEST + codes + response = requests.get(status_test_url, headers=HEADERS) + SORT_STATUS_CODE = str(response.status_code) + SORT_STATUS_DESC = http_status_codes.get(SORT_STATUS_CODE, "Unknown Status Code") + print_http_status(SORT_STATUS_CODE, SORT_STATUS_DESC) + response.close() + +print(f" | ✂️ Disconnected from {JSON_GET_URL}") + print("Finished!") From 24e197d9d291ef5adab89807b9233c3c43199b5d Mon Sep 17 00:00:00 2001 From: DJDevon3 <49322231+DJDevon3@users.noreply.github.com> Date: Tue, 26 Mar 2024 02:30:31 -0400 Subject: [PATCH 03/13] fix duplicate variable for url, correct status url --- examples/wifi/requests_wifi_advanced.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/examples/wifi/requests_wifi_advanced.py b/examples/wifi/requests_wifi_advanced.py index 00cdf25..1040d06 100644 --- a/examples/wifi/requests_wifi_advanced.py +++ b/examples/wifi/requests_wifi_advanced.py @@ -15,9 +15,6 @@ ssid = os.getenv("CIRCUITPY_WIFI_SSID") password = os.getenv("CIRCUITPY_WIFI_PASSWORD") -JSON_GET_URL = "https://httpbin.org/get" -STATUS_TEST = "https://httpbin.org/status/" - # Initalize Wifi, Socket Pool, Request Session pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio) ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio) @@ -104,6 +101,8 @@ def print_http_status(code, description): "511": "Network Authentication Required", } +JSON_GET_URL = "https://httpbin.org/get" +STATUS_TEST = "https://httpbin.org/status/" print(f"\nConnecting to {ssid}...") print(f"Signal Strength: {rssi}") @@ -114,8 +113,6 @@ def print_http_status(code, description): print(f"❌ OSError: {e}") print("✅ Wifi!") -JSON_GET_URL = "https://httpbin.org/get" - # Define a custom header as a dict. HEADERS = {"user-agent": "blinka/1.0.0"} @@ -134,8 +131,8 @@ def print_http_status(code, description): response.close() print(f" | ✂️ Disconnected from {JSON_GET_URL}") print(" | ") -print(f" | Status Code Test: {JSON_GET_URL}") +print(f" | Status Code Test: {STATUS_TEST}") # Some return errors then confirm the error (that's a good thing) # Demonstrates not all errors have the same behavior # 300, 304, and 306 in particular From c7ff5ccbde4ba67b779d309031396d0d32f01988 Mon Sep 17 00:00:00 2001 From: DJDevon3 <49322231+DJDevon3@users.noreply.github.com> Date: Tue, 26 Mar 2024 02:47:00 -0400 Subject: [PATCH 04/13] added ChatGPT attribution --- examples/wifi/requests_wifi_advanced.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/wifi/requests_wifi_advanced.py b/examples/wifi/requests_wifi_advanced.py index 1040d06..b12fa1d 100644 --- a/examples/wifi/requests_wifi_advanced.py +++ b/examples/wifi/requests_wifi_advanced.py @@ -1,6 +1,8 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT # Updated for Circuit Python 9.0 +# https://help.openai.com/en/articles/6825453-chatgpt-release-notes +# https://chat.openai.com/share/32ef0c5f-ac92-4d36-9d1e-0f91e0c4c574 """ WiFi Advanced (User-Agent & Status Codes) Example """ # pylint: disable=import-error From 09f8e3751412a3b6dd2f1fcb8fb2e268001a9d70 Mon Sep 17 00:00:00 2001 From: DJDevon3 <49322231+DJDevon3@users.noreply.github.com> Date: Tue, 2 Apr 2024 02:52:31 -0400 Subject: [PATCH 05/13] removed pylint: disable=import-error cleaning up discrepancy between my local pylint and adafruit actions. --- examples/wifi/requests_wifi_advanced.py | 1 - 1 file changed, 1 deletion(-) diff --git a/examples/wifi/requests_wifi_advanced.py b/examples/wifi/requests_wifi_advanced.py index b12fa1d..6d9d24d 100644 --- a/examples/wifi/requests_wifi_advanced.py +++ b/examples/wifi/requests_wifi_advanced.py @@ -4,7 +4,6 @@ # https://help.openai.com/en/articles/6825453-chatgpt-release-notes # https://chat.openai.com/share/32ef0c5f-ac92-4d36-9d1e-0f91e0c4c574 """ WiFi Advanced (User-Agent & Status Codes) Example """ -# pylint: disable=import-error import os From 4f0c265c0cf643774f75cb2e7eb6bccb834ae02a Mon Sep 17 00:00:00 2001 From: DJDevon3 <49322231+DJDevon3@users.noreply.github.com> Date: Thu, 11 Apr 2024 02:37:04 -0400 Subject: [PATCH 06/13] split advanced and status codes into separate examples --- examples/wifi/requests_wifi_advanced.py | 131 +++-------------- examples/wifi/requests_wifi_status_codes.py | 150 ++++++++++++++++++++ 2 files changed, 170 insertions(+), 111 deletions(-) create mode 100644 examples/wifi/requests_wifi_status_codes.py diff --git a/examples/wifi/requests_wifi_advanced.py b/examples/wifi/requests_wifi_advanced.py index 6d9d24d..86ffc34 100644 --- a/examples/wifi/requests_wifi_advanced.py +++ b/examples/wifi/requests_wifi_advanced.py @@ -1,9 +1,8 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT # Updated for Circuit Python 9.0 -# https://help.openai.com/en/articles/6825453-chatgpt-release-notes -# https://chat.openai.com/share/32ef0c5f-ac92-4d36-9d1e-0f91e0c4c574 -""" WiFi Advanced (User-Agent & Status Codes) Example """ + +""" WiFi Advanced Example """ import os @@ -22,88 +21,7 @@ requests = adafruit_requests.Session(pool, ssl_context) rssi = wifi.radio.ap_info.rssi - -def print_http_status(code, description): - """Returns HTTP status code and description""" - if "100" <= code <= "103": - print(f" | ✅ Status Test: {code} - {description}") - elif "200" <= code <= "299": - print(f" | ✅ Status Test: {code} - {description}") - elif "300" <= code <= "600": - print(f" | ❌ Status Test: {code} - {description}") - else: - print(f" | Unknown Response Status: {code} - {description}") - - -# All HTTP Status Codes -http_status_codes = { - "100": "Continue", - "101": "Switching Protocols", - "102": "Processing", - "103": "Early Hints", - "200": "OK", - "201": "Created", - "202": "Accepted", - "203": "Non-Authoritative Information", - "204": "No Content", - "205": "Reset Content", - "206": "Partial Content", - "207": "Multi-Status", - "208": "Already Reported", - "226": "IM Used", - "300": "Multiple Choices", - "301": "Moved Permanently", - "302": "Found", - "303": "See Other", - "304": "Not Modified", - "305": "Use Proxy", - "306": "Unused", - "307": "Temporary Redirect", - "308": "Permanent Redirect", - "400": "Bad Request", - "401": "Unauthorized", - "402": "Payment Required", - "403": "Forbidden", - "404": "Not Found", - "405": "Method Not Allowed", - "406": "Not Acceptable", - "407": "Proxy Authentication Required", - "408": "Request Timeout", - "409": "Conflict", - "410": "Gone", - "411": "Length Required", - "412": "Precondition Failed", - "413": "Payload Too Large", - "414": "URI Too Long", - "415": "Unsupported Media Type", - "416": "Range Not Satisfiable", - "417": "Expectation Failed", - "418": "I'm a teapot", - "421": "Misdirected Request", - "422": "Unprocessable Entity", - "423": "Locked", - "424": "Failed Dependency", - "425": "Too Early", - "426": "Upgrade Required", - "428": "Precondition Required", - "429": "Too Many Requests", - "431": "Request Header Fields Too Large", - "451": "Unavailable For Legal Reasons", - "500": "Internal Server Error", - "501": "Not Implemented", - "502": "Bad Gateway", - "503": "Service Unavailable", - "504": "Gateway Timeout", - "505": "HTTP Version Not Supported", - "506": "Variant Also Negotiates", - "507": "Insufficient Storage", - "508": "Loop Detected", - "510": "Not Extended", - "511": "Network Authentication Required", -} - JSON_GET_URL = "https://httpbin.org/get" -STATUS_TEST = "https://httpbin.org/status/" print(f"\nConnecting to {ssid}...") print(f"Signal Strength: {rssi}") @@ -115,36 +33,27 @@ def print_http_status(code, description): print("✅ Wifi!") # Define a custom header as a dict. -HEADERS = {"user-agent": "blinka/1.0.0"} +headers = {"user-agent": "blinka/1.0.0"} +print(f" | Fetching JSON: {JSON_GET_URL}") -print(f" | GET JSON: {JSON_GET_URL}") -response = requests.get(JSON_GET_URL, headers=HEADERS) +# GET JSON +response = requests.get(JSON_GET_URL, headers=headers) +content_type = response.headers.get("content-type", "") +date = response.headers.get("date", "") json_data = response.json() -HEADERS = json_data["headers"] -print(f" | User-Agent: {HEADERS['User-Agent']}") - -# HTTP STATUS CODE TESTING -# https://developer.mozilla.org/en-US/docs/Web/HTTP/Status -STATUS_CODE = str(response.status_code) -STATUS_DESCRIPTION = http_status_codes.get(STATUS_CODE, "Unknown Status Code") -print_http_status(STATUS_CODE, STATUS_DESCRIPTION) +headers = json_data["headers"] + +# JSON Response +if response.status_code == 200: + print(f" | 🆗 Status Code: {response.status_code}") +else: + print(f" | | Status Code: {response.status_code}") +print(f" | ✅ Custom User-Agent Header: {headers['User-Agent']}") +print(f" | ✅ Content-Type: {content_type}") +print(f" | ✅ Response Timestamp: {date}") + +# Close, delete and collect the response data response.close() -print(f" | ✂️ Disconnected from {JSON_GET_URL}") -print(" | ") - -print(f" | Status Code Test: {STATUS_TEST}") -# Some return errors then confirm the error (that's a good thing) -# Demonstrates not all errors have the same behavior -# 300, 304, and 306 in particular -for codes in sorted(http_status_codes.keys(), key=int): - status_test_url = STATUS_TEST + codes - response = requests.get(status_test_url, headers=HEADERS) - SORT_STATUS_CODE = str(response.status_code) - SORT_STATUS_DESC = http_status_codes.get(SORT_STATUS_CODE, "Unknown Status Code") - print_http_status(SORT_STATUS_CODE, SORT_STATUS_DESC) - response.close() print(f" | ✂️ Disconnected from {JSON_GET_URL}") - -print("Finished!") diff --git a/examples/wifi/requests_wifi_status_codes.py b/examples/wifi/requests_wifi_status_codes.py new file mode 100644 index 0000000..10e84d8 --- /dev/null +++ b/examples/wifi/requests_wifi_status_codes.py @@ -0,0 +1,150 @@ +# SPDX-FileCopyrightText: 2024 DJDevon3 +# SPDX-License-Identifier: MIT +# Updated for Circuit Python 9.0 +# https://help.openai.com/en/articles/6825453-chatgpt-release-notes +# https://chat.openai.com/share/32ef0c5f-ac92-4d36-9d1e-0f91e0c4c574 +""" WiFi Advanced (User-Agent & Status Codes) Example """ + +import os + +import adafruit_connection_manager +import wifi + +import adafruit_requests + +# Get WiFi details, ensure these are setup in settings.toml +ssid = os.getenv("CIRCUITPY_WIFI_SSID") +password = os.getenv("CIRCUITPY_WIFI_PASSWORD") + +# Initalize Wifi, Socket Pool, Request Session +pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio) +ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio) +requests = adafruit_requests.Session(pool, ssl_context) +rssi = wifi.radio.ap_info.rssi + + +def print_http_status(code, description): + """Returns HTTP status code and description""" + if "100" <= code <= "103": + print(f" | ✅ Status Test: {code} - {description}") + elif "200" <= code <= "299": + print(f" | ✅ Status Test: {code} - {description}") + elif "300" <= code <= "600": + print(f" | ❌ Status Test: {code} - {description}") + else: + print(f" | Unknown Response Status: {code} - {description}") + + +# All HTTP Status Codes +http_status_codes = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "Unused", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Too Early", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "510": "Not Extended", + "511": "Network Authentication Required", +} + +JSON_GET_URL = "https://httpbin.org/get" +STATUS_TEST = "https://httpbin.org/status/" + +print(f"\nConnecting to {ssid}...") +print(f"Signal Strength: {rssi}") +try: + # Connect to the Wi-Fi network + wifi.radio.connect(ssid, password) +except OSError as e: + print(f"❌ OSError: {e}") +print("✅ Wifi!") + +# Define a custom header as a dict. +HEADERS = {"user-agent": "blinka/1.0.0"} + +print(f" | GET JSON: {JSON_GET_URL}") +response = requests.get(JSON_GET_URL, headers=HEADERS) + +json_data = response.json() +HEADERS = json_data["headers"] +print(f" | User-Agent: {HEADERS['User-Agent']}") + +# HTTP STATUS CODE TESTING +# https://developer.mozilla.org/en-US/docs/Web/HTTP/Status +STATUS_CODE = str(response.status_code) +STATUS_DESCRIPTION = http_status_codes.get(STATUS_CODE, "Unknown Status Code") +print_http_status(STATUS_CODE, STATUS_DESCRIPTION) +response.close() +print(f" | ✂️ Disconnected from {JSON_GET_URL}") +print(" | ") + +print(f" | Status Code Test: {STATUS_TEST}") +# Some return errors then confirm the error (that's a good thing) +# Demonstrates not all errors have the same behavior +# 300, 304, and 306 in particular +for codes in sorted(http_status_codes.keys(), key=int): + status_test_url = STATUS_TEST + codes + response = requests.get(status_test_url, headers=HEADERS) + SORT_STATUS_CODE = str(response.status_code) + SORT_STATUS_DESC = http_status_codes.get(SORT_STATUS_CODE, "Unknown Status Code") + print_http_status(SORT_STATUS_CODE, SORT_STATUS_DESC) + response.close() + +print(f" | ✂️ Disconnected from {JSON_GET_URL}") + +print("Finished!") From 908077dee0cb6649d76048a298ed314b237a0214 Mon Sep 17 00:00:00 2001 From: DJDevon3 <49322231+DJDevon3@users.noreply.github.com> Date: Thu, 11 Apr 2024 09:24:47 -0400 Subject: [PATCH 07/13] requested changes added additional http headers, removed most status codes for separate example --- examples/wifi/requests_wifi_advanced.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/wifi/requests_wifi_advanced.py b/examples/wifi/requests_wifi_advanced.py index 86ffc34..225e914 100644 --- a/examples/wifi/requests_wifi_advanced.py +++ b/examples/wifi/requests_wifi_advanced.py @@ -49,9 +49,9 @@ print(f" | 🆗 Status Code: {response.status_code}") else: print(f" | | Status Code: {response.status_code}") -print(f" | ✅ Custom User-Agent Header: {headers['User-Agent']}") -print(f" | ✅ Content-Type: {content_type}") -print(f" | ✅ Response Timestamp: {date}") +print(f" | | Custom User-Agent Header: {headers['User-Agent']}") +print(f" | | Content-Type: {content_type}") +print(f" | | Response Timestamp: {date}") # Close, delete and collect the response data response.close() From e341d972a8a865d20548e2918fff1141e9021862 Mon Sep 17 00:00:00 2001 From: DJDevon3 <49322231+DJDevon3@users.noreply.github.com> Date: Thu, 11 Apr 2024 09:50:05 -0400 Subject: [PATCH 08/13] updated docstring description --- examples/wifi/requests_wifi_status_codes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/wifi/requests_wifi_status_codes.py b/examples/wifi/requests_wifi_status_codes.py index 10e84d8..2214e92 100644 --- a/examples/wifi/requests_wifi_status_codes.py +++ b/examples/wifi/requests_wifi_status_codes.py @@ -3,7 +3,7 @@ # Updated for Circuit Python 9.0 # https://help.openai.com/en/articles/6825453-chatgpt-release-notes # https://chat.openai.com/share/32ef0c5f-ac92-4d36-9d1e-0f91e0c4c574 -""" WiFi Advanced (User-Agent & Status Codes) Example """ +""" WiFi Status Codes Example """ import os From 9b1917835c059618b52b93bce41b21512bde7050 Mon Sep 17 00:00:00 2001 From: DJDevon3 <49322231+DJDevon3@users.noreply.github.com> Date: Mon, 15 Apr 2024 12:59:03 -0400 Subject: [PATCH 09/13] changed to with statement and removed additional url This is more like the original advanced example. --- examples/wifi/requests_wifi_advanced.py | 41 +++++++++++-------------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/examples/wifi/requests_wifi_advanced.py b/examples/wifi/requests_wifi_advanced.py index 225e914..473078a 100644 --- a/examples/wifi/requests_wifi_advanced.py +++ b/examples/wifi/requests_wifi_advanced.py @@ -21,7 +21,10 @@ requests = adafruit_requests.Session(pool, ssl_context) rssi = wifi.radio.ap_info.rssi +# URL for GET request JSON_GET_URL = "https://httpbin.org/get" +# Define a custom header as a dict. +headers = {"user-agent": "blinka/1.0.0"} print(f"\nConnecting to {ssid}...") print(f"Signal Strength: {rssi}") @@ -34,26 +37,18 @@ # Define a custom header as a dict. headers = {"user-agent": "blinka/1.0.0"} -print(f" | Fetching JSON: {JSON_GET_URL}") - -# GET JSON -response = requests.get(JSON_GET_URL, headers=headers) -content_type = response.headers.get("content-type", "") -date = response.headers.get("date", "") - -json_data = response.json() -headers = json_data["headers"] - -# JSON Response -if response.status_code == 200: - print(f" | 🆗 Status Code: {response.status_code}") -else: - print(f" | | Status Code: {response.status_code}") -print(f" | | Custom User-Agent Header: {headers['User-Agent']}") -print(f" | | Content-Type: {content_type}") -print(f" | | Response Timestamp: {date}") - -# Close, delete and collect the response data -response.close() - -print(f" | ✂️ Disconnected from {JSON_GET_URL}") +print(" | Fetching JSON data from %s..." % JSON_GET_URL) + +# Use with statement for retreiving GET request data +with requests.get(JSON_GET_URL, headers=headers) as response: + json_data = response.json() + headers = json_data["headers"] + content_type = response.headers.get("content-type", "") + date = response.headers.get("date", "") + if response.status_code == 200: + print(f" | 🆗 Status Code: {response.status_code}") + else: + print(f" | | Status Code: {response.status_code}") + print(f" | | Custom User-Agent Header: {headers['User-Agent']}") + print(f" | | Content-Type: {content_type}") + print(f" | | Response Timestamp: {date}") From 7cecdd55b1f6bc7eb1741afc291605ef2e06729c Mon Sep 17 00:00:00 2001 From: DJDevon3 <49322231+DJDevon3@users.noreply.github.com> Date: Mon, 15 Apr 2024 13:16:13 -0400 Subject: [PATCH 10/13] added x emoji if response not ok --- examples/wifi/requests_wifi_advanced.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/wifi/requests_wifi_advanced.py b/examples/wifi/requests_wifi_advanced.py index 473078a..7afc00f 100644 --- a/examples/wifi/requests_wifi_advanced.py +++ b/examples/wifi/requests_wifi_advanced.py @@ -48,7 +48,7 @@ if response.status_code == 200: print(f" | 🆗 Status Code: {response.status_code}") else: - print(f" | | Status Code: {response.status_code}") + print(f" | ❌ Status Code: {response.status_code}") print(f" | | Custom User-Agent Header: {headers['User-Agent']}") print(f" | | Content-Type: {content_type}") print(f" | | Response Timestamp: {date}") From 7e30fb634adbc05b75dc0a92d9aaa7a3b60bb038 Mon Sep 17 00:00:00 2001 From: DJDevon3 <49322231+DJDevon3@users.noreply.github.com> Date: Mon, 15 Apr 2024 13:19:29 -0400 Subject: [PATCH 11/13] change fetching json data to fetching URL --- examples/wifi/requests_wifi_advanced.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/wifi/requests_wifi_advanced.py b/examples/wifi/requests_wifi_advanced.py index 7afc00f..bfad6af 100644 --- a/examples/wifi/requests_wifi_advanced.py +++ b/examples/wifi/requests_wifi_advanced.py @@ -37,7 +37,7 @@ # Define a custom header as a dict. headers = {"user-agent": "blinka/1.0.0"} -print(" | Fetching JSON data from %s..." % JSON_GET_URL) +print(f" | Fetching URL {JSON_GET_URL}") # Use with statement for retreiving GET request data with requests.get(JSON_GET_URL, headers=headers) as response: From b175c9b290425091cb0bf4bb5d6e0c260ef0b868 Mon Sep 17 00:00:00 2001 From: DJDevon3 <49322231+DJDevon3@users.noreply.github.com> Date: Sun, 21 Apr 2024 23:47:58 -0400 Subject: [PATCH 12/13] added with statement, changed status_test to status_test_url The variable is actually an http header status test so keeping it as url instead of json_url for that one is good. --- examples/wifi/requests_wifi_status_codes.py | 64 +++++++++++---------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/examples/wifi/requests_wifi_status_codes.py b/examples/wifi/requests_wifi_status_codes.py index 2214e92..a7d84d4 100644 --- a/examples/wifi/requests_wifi_status_codes.py +++ b/examples/wifi/requests_wifi_status_codes.py @@ -27,7 +27,9 @@ def print_http_status(code, description): """Returns HTTP status code and description""" if "100" <= code <= "103": print(f" | ✅ Status Test: {code} - {description}") - elif "200" <= code <= "299": + elif "200" == code: + print(f" | 🆗 Status Test: {code} - {description}") + elif "201" <= code <= "299": print(f" | ✅ Status Test: {code} - {description}") elif "300" <= code <= "600": print(f" | ❌ Status Test: {code} - {description}") @@ -103,7 +105,7 @@ def print_http_status(code, description): } JSON_GET_URL = "https://httpbin.org/get" -STATUS_TEST = "https://httpbin.org/status/" +STATUS_TEST_URL = "https://httpbin.org/status/" print(f"\nConnecting to {ssid}...") print(f"Signal Strength: {rssi}") @@ -118,33 +120,33 @@ def print_http_status(code, description): HEADERS = {"user-agent": "blinka/1.0.0"} print(f" | GET JSON: {JSON_GET_URL}") -response = requests.get(JSON_GET_URL, headers=HEADERS) - -json_data = response.json() -HEADERS = json_data["headers"] -print(f" | User-Agent: {HEADERS['User-Agent']}") - -# HTTP STATUS CODE TESTING -# https://developer.mozilla.org/en-US/docs/Web/HTTP/Status -STATUS_CODE = str(response.status_code) -STATUS_DESCRIPTION = http_status_codes.get(STATUS_CODE, "Unknown Status Code") -print_http_status(STATUS_CODE, STATUS_DESCRIPTION) -response.close() -print(f" | ✂️ Disconnected from {JSON_GET_URL}") -print(" | ") - -print(f" | Status Code Test: {STATUS_TEST}") -# Some return errors then confirm the error (that's a good thing) -# Demonstrates not all errors have the same behavior -# 300, 304, and 306 in particular -for codes in sorted(http_status_codes.keys(), key=int): - status_test_url = STATUS_TEST + codes - response = requests.get(status_test_url, headers=HEADERS) - SORT_STATUS_CODE = str(response.status_code) - SORT_STATUS_DESC = http_status_codes.get(SORT_STATUS_CODE, "Unknown Status Code") - print_http_status(SORT_STATUS_CODE, SORT_STATUS_DESC) +with requests.get(JSON_GET_URL, headers=HEADERS) as response: + json_data = response.json() + HEADERS = json_data["headers"] + print(f" | User-Agent: {HEADERS['User-Agent']}") + + # HTTP STATUS CODE TESTING + # https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + STATUS_CODE = str(response.status_code) + STATUS_DESCRIPTION = http_status_codes.get(STATUS_CODE, "Unknown Status Code") + print_http_status(STATUS_CODE, STATUS_DESCRIPTION) response.close() - -print(f" | ✂️ Disconnected from {JSON_GET_URL}") - -print("Finished!") + print(f" | ✂️ Disconnected from {JSON_GET_URL}") + print(" | ") + + print(f" | Status Code Test: {STATUS_TEST_URL}") + # Some return errors then confirm the error (that's a good thing) + # Demonstrates not all errors have the same behavior + # 300, 304, and 306 in particular + for codes in sorted(http_status_codes.keys(), key=int): + header_status_test_url = STATUS_TEST_URL + codes + response = requests.get(header_status_test_url, headers=HEADERS) + SORT_STATUS_CODE = str(response.status_code) + SORT_STATUS_DESC = http_status_codes.get( + SORT_STATUS_CODE, "Unknown Status Code" + ) + print_http_status(SORT_STATUS_CODE, SORT_STATUS_DESC) + + print(f" | ✂️ Disconnected from {JSON_GET_URL}") + + print("Finished!") From 7c45cdde710e01c3f8a5192cffdce2d6793f1253 Mon Sep 17 00:00:00 2001 From: foamyguy Date: Sat, 27 Apr 2024 09:34:35 -0500 Subject: [PATCH 13/13] merge main. remove single request before status codes loop. Use with context inside status codes loop. Add expected code to print out. --- .../requests_wifi_status_codes.py | 78 +++++++++---------- 1 file changed, 37 insertions(+), 41 deletions(-) rename examples/wifi/{ => expanded}/requests_wifi_status_codes.py (62%) diff --git a/examples/wifi/requests_wifi_status_codes.py b/examples/wifi/expanded/requests_wifi_status_codes.py similarity index 62% rename from examples/wifi/requests_wifi_status_codes.py rename to examples/wifi/expanded/requests_wifi_status_codes.py index a7d84d4..036b7bb 100644 --- a/examples/wifi/requests_wifi_status_codes.py +++ b/examples/wifi/expanded/requests_wifi_status_codes.py @@ -6,6 +6,7 @@ """ WiFi Status Codes Example """ import os +import time import adafruit_connection_manager import wifi @@ -23,18 +24,29 @@ rssi = wifi.radio.ap_info.rssi -def print_http_status(code, description): +def print_http_status(expected_code, actual_code, description): """Returns HTTP status code and description""" - if "100" <= code <= "103": - print(f" | ✅ Status Test: {code} - {description}") - elif "200" == code: - print(f" | 🆗 Status Test: {code} - {description}") - elif "201" <= code <= "299": - print(f" | ✅ Status Test: {code} - {description}") - elif "300" <= code <= "600": - print(f" | ❌ Status Test: {code} - {description}") + if "100" <= actual_code <= "103": + print( + f" | ✅ Status Test Expected: {expected_code} Actual: {actual_code} - {description}" + ) + elif "200" == actual_code: + print( + f" | 🆗 Status Test Expected: {expected_code} Actual: {actual_code} - {description}" + ) + elif "201" <= actual_code <= "299": + print( + f" | ✅ Status Test Expected: {expected_code} Actual: {actual_code} - {description}" + ) + elif "300" <= actual_code <= "600": + print( + f" | ❌ Status Test Expected: {expected_code} Actual: {actual_code} - {description}" + ) else: - print(f" | Unknown Response Status: {code} - {description}") + print( + f" | Unknown Response Status Expected: {expected_code} " + + f"Actual: {actual_code} - {description}" + ) # All HTTP Status Codes @@ -104,7 +116,6 @@ def print_http_status(code, description): "511": "Network Authentication Required", } -JSON_GET_URL = "https://httpbin.org/get" STATUS_TEST_URL = "https://httpbin.org/status/" print(f"\nConnecting to {ssid}...") @@ -116,37 +127,22 @@ def print_http_status(code, description): print(f"❌ OSError: {e}") print("✅ Wifi!") -# Define a custom header as a dict. -HEADERS = {"user-agent": "blinka/1.0.0"} - -print(f" | GET JSON: {JSON_GET_URL}") -with requests.get(JSON_GET_URL, headers=HEADERS) as response: - json_data = response.json() - HEADERS = json_data["headers"] - print(f" | User-Agent: {HEADERS['User-Agent']}") - # HTTP STATUS CODE TESTING - # https://developer.mozilla.org/en-US/docs/Web/HTTP/Status - STATUS_CODE = str(response.status_code) - STATUS_DESCRIPTION = http_status_codes.get(STATUS_CODE, "Unknown Status Code") - print_http_status(STATUS_CODE, STATUS_DESCRIPTION) - response.close() - print(f" | ✂️ Disconnected from {JSON_GET_URL}") - print(" | ") - - print(f" | Status Code Test: {STATUS_TEST_URL}") - # Some return errors then confirm the error (that's a good thing) - # Demonstrates not all errors have the same behavior - # 300, 304, and 306 in particular - for codes in sorted(http_status_codes.keys(), key=int): - header_status_test_url = STATUS_TEST_URL + codes - response = requests.get(header_status_test_url, headers=HEADERS) - SORT_STATUS_CODE = str(response.status_code) +print(f" | Status Code Test: {STATUS_TEST_URL}") +# Some return errors then confirm the error (that's a good thing) +# Demonstrates not all errors have the same behavior +# Some 300 level responses contain redirects that requests automatically follows +# By default the response object will contain the status code from the final +# response after all redirect, so it can differ from the expected status code. +for current_code in sorted(http_status_codes.keys(), key=int): + header_status_test_url = STATUS_TEST_URL + current_code + with requests.get(header_status_test_url) as response: + response_status_code = str(response.status_code) SORT_STATUS_DESC = http_status_codes.get( - SORT_STATUS_CODE, "Unknown Status Code" + response_status_code, "Unknown Status Code" ) - print_http_status(SORT_STATUS_CODE, SORT_STATUS_DESC) - - print(f" | ✂️ Disconnected from {JSON_GET_URL}") + print_http_status(current_code, response_status_code, SORT_STATUS_DESC) - print("Finished!") + # Rate limit ourselves a little to avoid strain on server + time.sleep(0.5) +print("Finished!")