Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add context manager vs explicit close() example #185

Closed
wants to merge 5 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions examples/wifi/requests_wifi_context_manager_basics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# SPDX-FileCopyrightText: 2024 DJDevon3
# SPDX-License-Identifier: MIT
# Updated for Circuit Python 9.0
""" WiFi Context Manager Basics 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

JSON_GET_URL = "https://httpbin.org/get"

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!\n")

print("-" * 40)

# This method requires an explicit close
print("Explicit Close() Example")
response = requests.get(JSON_GET_URL)
print(" | ✅ Connected to JSON")

json_data = response.json()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I am understanding the conversation here correctly I think it makes the most sense to switch reponse.json() here to use response.text() instead. Then if you want you can use json.loads to parse it and get the data out.

That way the one that is illustrating the manual call to close() is serving it's intended purpose about illustrating the necessity to close afterward when the context processor isn't in use.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't matter if I do data = response.text or data = response.json both are available after the explicit close because both are being buffered into the data variable. Can you post an example of what you mean because I'm not understanding the difference in use. Yes .text will print out the raw json data format and .json prints out a parsed version. With regards to .close() I'm not seeing any difference in behavior because the data variable acts as a buffer.

if response.status_code == 200:
print(f" | 🆗 Status Code: {response.status_code}")
else:
print(f" | | Status Code: {response.status_code}")
headers = json_data["headers"]
date = response.headers.get("date", "")
print(f" | | Response Timestamp: {date}")

# Close response manually (prone to mid-disconnect socket errors, out of retries)
response.close()
print(f" | ✂️ Disconnected from {JSON_GET_URL}")
print("-" * 40)

print("versus")

print("-" * 40)

# Closing response is included automatically using "with"
print("Context Manager WITH Example")
response = requests.get(JSON_GET_URL)
print(" | ✅ Connected to JSON")

# Wrap a request using a with statement
with requests.get(JSON_GET_URL) as response:
date = response.headers.get("date", "")
json_data = response.json()
if response.status_code == 200:
print(f" | 🆗 Status Code: {response.status_code}")
else:
print(f" | | Status Code: {response.status_code}")
headers = json_data["headers"]
print(f" | | Response Timestamp: {date}")

# Notice there is no response.close() here
# It's handled automatically in a with statement
# This is the better way.
print(f" | ✂️ Disconnected from {JSON_GET_URL}")

print("-" * 40)

print("\nBoth examples are functionally identical")
print(
"However, a with statement is more robust against disconnections mid-request "
+ "and automatically closes the response."
)
print("Using with statements for requests is recommended\n\n")
Loading