Skip to content

Commit 57046b7

Browse files
committed
accept url encoded form post data
1 parent 207d939 commit 57046b7

File tree

1 file changed

+26
-6
lines changed

1 file changed

+26
-6
lines changed

gurgleapps_webserver.py

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -131,12 +131,24 @@ async def serve_request(self, reader, writer):
131131
if content_length > 0:
132132
post_data_raw = await reader.readexactly(content_length)
133133
print("POST data:", post_data_raw)
134-
try:
135-
post_data = json.loads(post_data_raw)
136-
except ValueError as e:
137-
print("Error decoding JSON data:", e)
138-
# Handle the error (e.g., send an error response to the client)
139-
await response.send("Invalid JSON data", status_code=400)
134+
content_type_header = "Content-Type: application/json" # default to JSON
135+
for header in headers:
136+
if header.lower().startswith("content-type:"):
137+
content_type_header = header
138+
break
139+
if "application/json" in content_type_header.lower():
140+
try:
141+
post_data = json.loads(post_data_raw)
142+
except ValueError as e:
143+
print("Error decoding JSON data:", e)
144+
# Handle the error (e.g., send an error response to the client)
145+
await response.send("Invalid JSON data", status_code=400)
146+
return
147+
elif "application/x-www-form-urlencoded" in content_type_header.lower():
148+
post_data = self.parse_form_data(post_data_raw.decode('utf-8'))
149+
else:
150+
# Handle unsupported content types
151+
await response.send("Unsupported content type", status_code=415)
140152
return
141153
request = Request(post_data)
142154
# check if the url is a function route and if so run the function
@@ -311,6 +323,14 @@ def blink_element(element, pin, duration=0.27):
311323
blink_element(element, led_pin)
312324
await asyncio.sleep(delay_between_digits if element != '.' else 2 * delay_between_digits)
313325
await asyncio.sleep(delay_between_repititions)
326+
327+
def parse_form_data(self, form_data_raw):
328+
form_data = {}
329+
for pair in form_data_raw.split('&'):
330+
key, value = pair.split('=')
331+
form_data[key] = value
332+
return form_data
333+
314334

315335
def list_files_and_folders(self, path):
316336
entries = uos.ilistdir(path)

0 commit comments

Comments
 (0)