Skip to content

Commit

Permalink
changed to with statement and removed additional url
Browse files Browse the repository at this point in the history
This is more like the original advanced example.
  • Loading branch information
DJDevon3 committed Apr 15, 2024
1 parent e341d97 commit 9b19178
Showing 1 changed file with 18 additions and 23 deletions.
41 changes: 18 additions & 23 deletions examples/wifi/requests_wifi_advanced.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand All @@ -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}")

0 comments on commit 9b19178

Please sign in to comment.