Skip to content

Commit

Permalink
merge main, resolve conflicts
Browse files Browse the repository at this point in the history
  • Loading branch information
FoamyGuy committed Jul 29, 2024
1 parent c97cc4b commit edef59a
Show file tree
Hide file tree
Showing 26 changed files with 162 additions and 134 deletions.
24 changes: 7 additions & 17 deletions adafruit_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,7 @@ def _read_from_buffer(

def _readinto(self, buf: bytearray) -> int:
if not self.socket:
raise RuntimeError(
"Newer Response closed this one. Use Responses immediately."
)
raise RuntimeError("Newer Response closed this one. Use Responses immediately.")

if not self._remaining:
# Consume the chunk header if need be.
Expand Down Expand Up @@ -280,10 +278,7 @@ def _parse_headers(self) -> None:

def _validate_not_gzip(self) -> None:
"""gzip encoding is not supported. Raise an exception if found."""
if (
"content-encoding" in self.headers
and self.headers["content-encoding"] == "gzip"
):
if "content-encoding" in self.headers and self.headers["content-encoding"] == "gzip":
raise ValueError(
"Content-encoding is gzip, data cannot be accessed as json or text. "
"Use content property to access raw bytes."
Expand Down Expand Up @@ -394,9 +389,7 @@ def _build_boundary_data(self, files: dict): # pylint: disable=too-many-locals
if len(field_values) >= 4:
file_headers = field_values[3]
for file_header_key, file_header_value in file_headers.items():
boundary_objects.append(
f"{file_header_key}: {file_header_value}\r\n"
)
boundary_objects.append(f"{file_header_key}: {file_header_value}\r\n")
boundary_objects.append("\r\n")

if hasattr(file_handle, "read"):
Expand Down Expand Up @@ -500,7 +493,8 @@ def _send_header(self, socket, header, value):
self._send_as_bytes(socket, value)
self._send(socket, b"\r\n")

def _send_request( # noqa: PLR0913 Too many arguments in function definition
# noqa: PLR0912 Too many branches
def _send_request( # noqa: PLR0913,PLR0912 Too many arguments in function definition,Too many branches
self,
socket: SocketType,
host: str,
Expand Down Expand Up @@ -543,9 +537,7 @@ def _send_request( # noqa: PLR0913 Too many arguments in function definition
data_is_file = False
boundary_objects = None
if files and isinstance(files, dict):
boundary_string, content_length, boundary_objects = (
self._build_boundary_data(files)
)
boundary_string, content_length, boundary_objects = self._build_boundary_data(files)
content_type_header = f"multipart/form-data; boundary={boundary_string}"
elif data and hasattr(data, "read"):
data_is_file = True
Expand Down Expand Up @@ -644,9 +636,7 @@ def request( # noqa: PLR0912,PLR0913,PLR0915 Too many branches,Too many argumen
)
ok = True
try:
self._send_request(
socket, host, method, path, headers, data, json, files
)
self._send_request(socket, host, method, path, headers, data, json, files)
except OSError as exc:
last_exc = exc
ok = False
Expand Down
4 changes: 1 addition & 3 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@
creation_year = "2019"
current_year = str(datetime.datetime.now().year)
year_duration = (
current_year
if current_year == creation_year
else creation_year + " - " + current_year
current_year if current_year == creation_year else creation_year + " - " + current_year
)
copyright = year_duration + " ladyada"
author = "ladyada"
Expand Down
4 changes: 1 addition & 3 deletions examples/wifi/expanded/requests_wifi_api_discord.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,7 @@ def time_calc(input_time):
DEBUG_RESPONSE = False

try:
with requests.get(
url=DISCORD_SOURCE, headers=DISCORD_HEADER
) as discord_response:
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}")
Expand Down
21 changes: 7 additions & 14 deletions examples/wifi/expanded/requests_wifi_api_fitbit.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@
password = os.getenv("CIRCUITPY_WIFI_PASSWORD")
Fitbit_ClientID = os.getenv("FITBIT_CLIENTID")
Fitbit_Token = os.getenv("FITBIT_ACCESS_TOKEN")
Fitbit_First_Refresh_Token = os.getenv(
"FITBIT_FIRST_REFRESH_TOKEN"
) # overides nvm first run only
Fitbit_First_Refresh_Token = os.getenv("FITBIT_FIRST_REFRESH_TOKEN") # overides nvm first run only
Fitbit_UserID = os.getenv("FITBIT_USERID")

# Set debug to True for full INTRADAY JSON response.
Expand Down Expand Up @@ -167,8 +165,7 @@ def time_calc(input_time):
print(" | Requesting authorization for next token")
if DEBUG:
print(
"FULL REFRESH TOKEN POST:"
+ f"{FITBIT_OAUTH_TOKEN}{FITBIT_OAUTH_REFRESH_TOKEN}"
"FULL REFRESH TOKEN POST:" + f"{FITBIT_OAUTH_TOKEN}{FITBIT_OAUTH_REFRESH_TOKEN}"
)
print(f"Current Refresh Token: {Refresh_Token}")
# TOKEN REFRESH POST
Expand Down Expand Up @@ -270,24 +267,20 @@ def time_calc(input_time):
try:
# Fitbit's sync to mobile device & server every 15 minutes in chunks.
# Pointless to poll their API faster than 15 minute intervals.
activities_heart_value = fitbit_json["activities-heart-intraday"][
"dataset"
]
activities_heart_value = fitbit_json["activities-heart-intraday"]["dataset"]
if MIDNIGHT_DEBUG:
RESPONSE_LENGTH = 0
else:
RESPONSE_LENGTH = len(activities_heart_value)
if RESPONSE_LENGTH >= 15:
activities_timestamp = fitbit_json["activities-heart"][0][
"dateTime"
]
activities_timestamp = fitbit_json["activities-heart"][0]["dateTime"]
print(f" | | Fitbit Date: {activities_timestamp}")
if MIDNIGHT_DEBUG:
ACTIVITIES_LATEST_HEART_TIME = "00:05:00"
else:
ACTIVITIES_LATEST_HEART_TIME = fitbit_json[
"activities-heart-intraday"
]["dataset"][RESPONSE_LENGTH - 1]["time"]
ACTIVITIES_LATEST_HEART_TIME = fitbit_json["activities-heart-intraday"][
"dataset"
][RESPONSE_LENGTH - 1]["time"]
print(f" | | Fitbit Time: {ACTIVITIES_LATEST_HEART_TIME[0:-3]}")
print(f" | | Today's Logged Pulses: {RESPONSE_LENGTH}")

Expand Down
4 changes: 1 addition & 3 deletions examples/wifi/expanded/requests_wifi_api_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,7 @@ def time_calc(input_time):
try:
print(" | Attempting to GET Github JSON!")
try:
with requests.get(
url=GITHUB_SOURCE, headers=GITHUB_HEADER
) as github_response:
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)
Expand Down
6 changes: 1 addition & 5 deletions examples/wifi/expanded/requests_wifi_api_mastodon.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,7 @@ def time_calc(input_time):

# Publicly available data no header required
MAST_SOURCE = (
"https://"
+ MASTODON_SERVER
+ "/api/v1/accounts/"
+ MASTODON_USERID
+ "/statuses?limit=1"
"https://" + MASTODON_SERVER + "/api/v1/accounts/" + MASTODON_USERID + "/statuses?limit=1"
)

while True:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,10 @@ def time_calc(input_time):


def _format_datetime(datetime):
return f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} {datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}"
return (
f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} "
f"{datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}"
)


while True:
Expand All @@ -87,9 +90,7 @@ 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:
with requests.get(
url=OPENSKY_SOURCE, headers=OPENSKY_HEADER
) as opensky_response:
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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,10 @@ def time_calc(input_time):


def _format_datetime(datetime):
return f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} {datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}"
return (
f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} "
f"{datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}"
)


while True:
Expand All @@ -100,9 +103,7 @@ def _format_datetime(datetime):
try:
print(" | Attempting to GET OpenSky-Network Area Flights JSON!")
try:
with requests.get(
url=OPENSKY_SOURCE, headers=OSN_HEADER
) as opensky_response:
with requests.get(url=OPENSKY_SOURCE, headers=OSN_HEADER) as opensky_response:
opensky_json = opensky_response.json()
except ConnectionError as e:
print("Connection Error:", e)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ def time_calc(input_time):


def _format_datetime(datetime):
return f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} {datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}"
return (
f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year} "
f"{datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}"
)


while True:
Expand Down
5 changes: 1 addition & 4 deletions examples/wifi/expanded/requests_wifi_api_twitch.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,7 @@ def _format_datetime(datetime):
"Client-Id": "" + TWITCH_CID + "",
}
TWITCH_FOLLOWERS_SOURCE = (
"https://api.twitch.tv/helix/channels"
+ "/followers?"
+ "broadcaster_id="
+ TWITCH_UID
"https://api.twitch.tv/helix/channels" + "/followers?" + "broadcaster_id=" + TWITCH_UID
)
print(" | Attempting to GET Twitch JSON!")
try:
Expand Down
Binary file modified examples/wifi/expanded/requests_wifi_file_upload_image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion examples/wifi/expanded/requests_wifi_multiple_cookies.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# SPDX-FileCopyrightText: 2022 Alec Delaney
# SPDX-License-Identifier: MIT
# Coded for Circuit Python 9.0
""" Multiple Cookies Example written for MagTag """
"""Multiple Cookies Example written for MagTag"""

import os

Expand Down
10 changes: 3 additions & 7 deletions examples/wifi/expanded/requests_wifi_rachio_irrigation.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,7 @@ def _format_datetime(datetime):
try:
print(" | Attempting to GET Rachio Authorization")
try:
with requests.get(
url=RACHIO_SOURCE, headers=RACHIO_HEADER
) as rachio_response:
with requests.get(url=RACHIO_SOURCE, headers=RACHIO_HEADER) as rachio_response:
rachio_json = rachio_response.json()
except ConnectionError as e:
print("Connection Error:", e)
Expand All @@ -127,9 +125,7 @@ def _format_datetime(datetime):
print(f"Failed to GET data: {e}")
time.sleep(60)
break
print(
"\nThis script can only continue when a proper APIKey & PersonID is used."
)
print("\nThis script can only continue when a proper APIKey & PersonID is used.")
print("\nFinished!")
print("===============================")
time.sleep(SLEEP_TIME)
Expand Down Expand Up @@ -191,7 +187,7 @@ def _format_datetime(datetime):
print(f" | | Unix Registration Date: {rachio_createdate}")
print(f" | | Unix Timezone Offset: {rachio_timezone_offset}")
current_struct_time = time.localtime(local_unix_time)
final_timestamp = "{}".format(_format_datetime(current_struct_time))
final_timestamp = f"{_format_datetime(current_struct_time)}"
print(f" | | Registration Date: {final_timestamp}")

rachio_devices = rachio_json["devices"][0]["name"]
Expand Down
22 changes: 6 additions & 16 deletions examples/wifi/expanded/requests_wifi_status_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 Status Codes Example """
"""WiFi Status Codes Example"""

import os
import time
Expand All @@ -27,21 +27,13 @@
def print_http_status(expected_code, actual_code, description):
"""Returns HTTP status code and description"""
if "100" <= actual_code <= "103":
print(
f" | ✅ Status Test Expected: {expected_code} Actual: {actual_code} - {description}"
)
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}"
)
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}"
)
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}"
)
print(f" | ❌ Status Test Expected: {expected_code} Actual: {actual_code} - {description}")
else:
print(
f" | Unknown Response Status Expected: {expected_code} "
Expand Down Expand Up @@ -138,9 +130,7 @@ def print_http_status(expected_code, actual_code, description):
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(
response_status_code, "Unknown Status Code"
)
SORT_STATUS_DESC = http_status_codes.get(response_status_code, "Unknown Status Code")
print_http_status(current_code, response_status_code, SORT_STATUS_DESC)

# Rate limit ourselves a little to avoid strain on server
Expand Down
2 changes: 1 addition & 1 deletion examples/wifi/requests_wifi_advanced.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# SPDX-License-Identifier: MIT
# Updated for Circuit Python 9.0

""" WiFi Advanced Example """
"""WiFi Advanced Example"""

import os

Expand Down
2 changes: 1 addition & 1 deletion examples/wifi/requests_wifi_simpletest.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
# Updated for Circuit Python 9.0
""" WiFi Simpletest """
"""WiFi Simpletest"""

import os

Expand Down
Loading

0 comments on commit edef59a

Please sign in to comment.