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

Use with in examples, remove close in json() #188

Merged
merged 1 commit into from
Apr 27, 2024
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion adafruit_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ def json(self) -> Any:
obj = json_module.load(self._raw)
if not self._cached:
self._cached = obj
self.close()

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Removed the .close() here, as it's not standard in CPython

return obj

def iter_content(self, chunk_size: int = 1, decode_unicode: bool = False) -> bytes:
Expand Down
24 changes: 10 additions & 14 deletions examples/cpython/requests_cpython_advanced.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
48 changes: 20 additions & 28 deletions examples/cpython/requests_cpython_simpletest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
21 changes: 9 additions & 12 deletions examples/esp32spi/requests_esp32spi_advanced.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
48 changes: 20 additions & 28 deletions examples/esp32spi/requests_esp32spi_simpletest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
21 changes: 9 additions & 12 deletions examples/fona/requests_fona_advanced.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
48 changes: 20 additions & 28 deletions examples/fona/requests_fona_simpletest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
6 changes: 4 additions & 2 deletions examples/wifi/expanded/requests_wifi_api_discord.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
15 changes: 7 additions & 8 deletions examples/wifi/expanded/requests_wifi_api_fitbit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

A few of these, I moved the initial connection into the try/except block

fitbit_json = fitbit_get_response.json()
except ConnectionError as e:
print("Connection Error:", e)
print("Retrying in 10 seconds")
Expand Down Expand Up @@ -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")
Expand Down
9 changes: 4 additions & 5 deletions examples/wifi/expanded/requests_wifi_api_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Comment on lines -95 to -96
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Removed these closes, and the disconnected message


print("\nFinished!")
print(f"Board Uptime: {time_calc(time.monotonic())}")
print(f"Next Update: {time_calc(SLEEP_TIME)}")
Expand Down
4 changes: 2 additions & 2 deletions examples/wifi/expanded/requests_wifi_api_mastodon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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)}")
Expand Down
Loading
Loading