Skip to content

Commit 2ac9269

Browse files
authored
Merge pull request #93 from makermelissa/master
Raise error on HTTP Error and fix json w/ no path
2 parents 4ffb7bf + 7e44178 commit 2ac9269

File tree

1 file changed

+30
-6
lines changed

1 file changed

+30
-6
lines changed

adafruit_pyportal.py

+30-6
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,10 @@
115115
CONTENT_IMAGE = const(3)
116116

117117

118+
class HttpError(Exception):
119+
"""HTTP Specific Error"""
120+
121+
118122
class Fake_Requests:
119123
"""For faking 'requests' using a local file instead of the network."""
120124

@@ -758,10 +762,25 @@ def wget(self, url, filename, *, chunk_size=12000):
758762

759763
self.neo_status((100, 100, 0))
760764
r = requests.get(url, stream=True)
765+
761766
headers = {}
762767
for title, content in r.headers.items():
763768
headers[title.lower()] = content
764769

770+
if r.status_code == 200:
771+
print("Reply is OK!")
772+
self.neo_status((0, 0, 100)) # green = got data
773+
else:
774+
if self._debug:
775+
if "content-length" in headers:
776+
print("Content-Length: {}".format(int(headers["content-length"])))
777+
if "date" in headers:
778+
print("Date: {}".format(headers["date"]))
779+
self.neo_status((100, 0, 0)) # red = http error
780+
raise HttpError(
781+
"Code {}: {}".format(r.status_code, r.reason.decode("utf-8"))
782+
)
783+
765784
if self._debug:
766785
print(headers)
767786
if "content-length" in headers:
@@ -938,9 +957,6 @@ def fetch(self, refresh_url=None, timeout=10):
938957
elif "application/javascript" in headers["content-type"]:
939958
content_type = CONTENT_JSON
940959
else:
941-
print(
942-
"HTTP Error {}: {}".format(r.status_code, r.reason.decode("utf-8"))
943-
)
944960
if self._debug:
945961
if "content-length" in headers:
946962
print(
@@ -949,7 +965,9 @@ def fetch(self, refresh_url=None, timeout=10):
949965
if "date" in headers:
950966
print("Date: {}".format(headers["date"]))
951967
self.neo_status((100, 0, 0)) # red = http error
952-
return None
968+
raise HttpError(
969+
"Code {}: {}".format(r.status_code, r.reason.decode("utf-8"))
970+
)
953971

954972
if self._debug and content_type == CONTENT_TEXT:
955973
print(r.text)
@@ -993,11 +1011,17 @@ def fetch(self, refresh_url=None, timeout=10):
9931011
except KeyError:
9941012
print(json_out)
9951013
raise
996-
elif self._regexp_path:
1014+
elif content_type == CONTENT_TEXT and self._regexp_path:
9971015
for regexp in self._regexp_path:
9981016
values.append(re.search(regexp, r.text).group(1))
9991017
else:
1000-
values = r.text
1018+
if content_type == CONTENT_JSON:
1019+
# No path given, so return JSON as string for compatibility
1020+
import json # pylint: disable=import-outside-toplevel
1021+
1022+
values = json.dumps(r.json())
1023+
else:
1024+
values = r.text
10011025

10021026
if self._image_json_path:
10031027
try:

0 commit comments

Comments
 (0)