-
Notifications
You must be signed in to change notification settings - Fork 37
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
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
d46deb2
add context manager vs explicit close() examples
DJDevon3 e72d22a
reworded socket to response per Anecdata suggestion
DJDevon3 067773c
reword comment for data still available after response closed suggest…
DJDevon3 88299d5
added Socket in Use count to show disconnection is real
DJDevon3 0aa7e0d
keep it simple, removed additional fluff
DJDevon3 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
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") |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 useresponse.text()
instead. Then if you want you can usejson.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.There was a problem hiding this comment.
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
ordata = 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.