PicoWireless: ppwhttp fix to support JSON content type

This is a bit of a fudge, and was only tested against the Cheerlights API.

Detects JSON content type, parses out the content length and truncates the response body to length.

Should probably do this *before* decoding from utf-8.

Updates cheerlights.py API example to support XML, JSON and TEXT endpoints.
pull/208/head
Phil Howard 2021-09-29 12:47:55 +01:00
rodzic 9f07be90da
commit eb3c8b0ebc
2 zmienionych plików z 31 dodań i 1 usunięć

Wyświetl plik

@ -1,4 +1,10 @@
import time
import json
try:
import xmltok # https://pypi.org/project/micropython-xmltok/
import io
except ImportError:
xmltok = None
from micropython import const
try:
@ -23,7 +29,23 @@ print("Local IP: {}.{}.{}.{}".format(*my_ip))
def handler(head, body):
if head["Status"] == "200 OK":
color = body[1:]
if HTTP_REQUEST_PATH.endswith(".json"):
# Parse as JSON
data = json.loads(body)
color = data['field2'][1:]
elif HTTP_REQUEST_PATH.endswith(".xml") and xmltok is not None:
# Parse as XML
data = xmltok.tokenize(io.StringIO(body))
color = xmltok.text_of(data, "field2")[1:]
elif HTTP_REQUEST_PATH.endswith(".txt"):
# Parse as plain text
color = body[1:]
else:
print("Unable to parse API response!")
return
r = int(color[0:2], 16)
g = int(color[2:4], 16)
b = int(color[4:6], 16)

Wyświetl plik

@ -158,6 +158,14 @@ Connection: close
key, value = line.split(": ", 1)
dhead[key] = value
# Fudge to handle JSON data type, which is prefixed with a content length.
# This ignores the charset, if specified, since we've already assumed utf-8 above!
# TODO maybe pay attention to Content-Type charset
if "Content-Type" in dhead and dhead["Content-Type"].startswith("application/json"):
length, body = body.split("\n", 1)
length = int(length, 16)
body = body[:length]
handler(dhead, body)
picowireless.client_stop(client_sock)