Skip to content

Commit ae38910

Browse files
committed
Handle HTTP errors and content type better
1 parent fb83623 commit ae38910

File tree

1 file changed

+53
-12
lines changed

1 file changed

+53
-12
lines changed

adafruit_pyportal.py

100644100755
Lines changed: 53 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
import os
4747
import time
4848
import gc
49+
from micropython import const
4950
import board
5051
import busio
5152
from digitalio import DigitalInOut
@@ -108,20 +109,29 @@
108109
LOCALFILE = "local.txt"
109110
# pylint: enable=line-too-long
110111

112+
CONTENT_TEXT = const(1)
113+
CONTENT_JSON = const(2)
114+
CONTENT_IMAGE = const(3)
115+
111116

112117
class Fake_Requests:
113118
"""For faking 'requests' using a local file instead of the network."""
114119

115120
def __init__(self, filename):
116121
self._filename = filename
117-
with open(filename, "r") as file:
118-
self.text = file.read()
119122

120123
def json(self):
121124
"""json parsed version for local requests."""
122125
import json # pylint: disable=import-outside-toplevel
123126

124-
return json.loads(self.text)
127+
with open(self._filename, "r") as file:
128+
return json.load(file)
129+
130+
@property
131+
def text(self):
132+
"""raw text version for local requests."""
133+
with open(self._filename, "r") as file:
134+
return file.read()
125135

126136

127137
class PyPortal:
@@ -729,14 +739,17 @@ def wget(self, url, filename, *, chunk_size=12000):
729739

730740
self.neo_status((100, 100, 0))
731741
r = requests.get(url, stream=True)
742+
headers = {}
743+
for title, content in r.headers.items():
744+
headers[title.lower()] = content
732745

733746
if self._debug:
734-
print(r.headers)
735-
if "content-length" in r.headers:
736-
content_length = int(r.headers["content-length"])
737-
remaining = content_length
747+
print(headers)
748+
if "content-length" in headers:
749+
content_length = int(headers["content-length"])
738750
else:
739-
raise RuntimeError("Content-length missing from headers")
751+
raise RuntimeError("Content-Length missing from headers")
752+
remaining = content_length
740753
print("Saving data to ", filename)
741754
stamp = time.monotonic()
742755
file = open(filename, "wb")
@@ -871,6 +884,7 @@ def fetch(self, refresh_url=None, timeout=10):
871884
json_out = None
872885
image_url = None
873886
values = []
887+
content_type = CONTENT_TEXT
874888

875889
gc.collect()
876890
if self._debug:
@@ -888,14 +902,41 @@ def fetch(self, refresh_url=None, timeout=10):
888902
self.neo_status((100, 100, 0)) # yellow = fetching data
889903
gc.collect()
890904
r = requests.get(self._url, headers=self._headers, timeout=timeout)
905+
headers = {}
906+
for title, content in r.headers.items():
907+
headers[title.lower()] = content
891908
gc.collect()
892-
self.neo_status((0, 0, 100)) # green = got data
893-
print("Reply is OK!")
909+
if self._debug:
910+
print("Headers:", headers)
911+
if r.status_code == 200:
912+
print("Reply is OK!")
913+
self.neo_status((0, 0, 100)) # green = got data
914+
if "content-type" in headers:
915+
if "image/" in headers["content-type"]:
916+
content_type = CONTENT_IMAGE
917+
elif "application/json" in headers["content-type"]:
918+
content_type = CONTENT_JSON
919+
else:
920+
print(
921+
"HTTP Error {}: {}".format(r.status_code, r.reason.decode("utf-8"))
922+
)
923+
if self._debug:
924+
if "content-length" in headers:
925+
print(
926+
"Content-Length: {}".format(int(headers["content-length"]))
927+
)
928+
if "date" in headers:
929+
print("Date: {}".format(headers["date"]))
930+
self.neo_status((100, 0, 0)) # red = http error
931+
return None
894932

895-
if self._debug and not self._image_json_path and not self._json_path:
933+
if self._debug and content_type == CONTENT_TEXT:
896934
print(r.text)
897935

898-
if self._image_json_path or self._json_path:
936+
if self._debug:
937+
print("Detected Content Type", content_type)
938+
939+
if content_type == CONTENT_JSON:
899940
try:
900941
gc.collect()
901942
json_out = r.json()

0 commit comments

Comments
 (0)