Retrieve values from HTML Form

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
hoanghuynh
Posts: 1
Joined: Wed Jan 17, 2018 4:35 am

Retrieve values from HTML Form

Post by hoanghuynh » Wed Jan 17, 2018 4:54 am

Hi guys ,
Very new to Python and Micropython, I need to retrieve values from a html form (textboxes).
My form is pretty simple

def handle_root(client):
myform = """
<form action="save_reco" method="post">
<input type="text" name="firstname" />
<br/>
<input type="text" name="lastname" />
<br/>
<input type="submit" value="Send" />
</form>
"""
send_response(client,myform)

def send_response(client, payload, status_code=200):
client.sendall("HTTP/1.0 {} OK\r\n".format(status_code))
client.sendall("Content-Type: text/html\r\n")
client.sendall("Content-Length: {}\r\n".format(len(payload)))
client.sendall("\r\n")

if len(payload) > 0:
client.sendall(payload)



my save_reco function looks like (it's based on several examples from the net).

def handle_save_reco(client, request):
match = ure.search("firstname=([^&]*)&lastname=(.*)",request)
print(match.group(0).decode("utf-8")
print(match.group(1).decode("utf-8")
....


def start(port=80):
addr = socket.getaddrinfo('0.0.0.0', port)[0][-1]
global server_socket
server_socket = socket.socket()
server_socket.bind(addr)
server_socket.listen(1)
while True:
client, addr = server_socket.accept()
client.settimeout(5.0)
request = b""
try:
while not "\r\n\r\n" in request:
request += client.recv(512)
except OSError:
pass
try:
url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP", request).group(1).decode("utf-8").rstrip("/")
except:
url = ure.search("(?:GET|POST) /(.*?)(?:\\?.*?)? HTTP", request).group(1).rstrip("/")
if url == "":
handle_root(client)
elif url == "save_reco":
handle_save_reco(client, request)
else:
handle_not_found(client, url)
client.close()



Problem is the the data comes empty when I submit the form.
I suppose I miss something :-(

cefn
Posts: 230
Joined: Tue Aug 09, 2016 10:58 am

Re: Retrieve values from HTML Form

Post by cefn » Tue Jan 23, 2018 10:00 pm

IN respect of the behaviour of the code you provide, what do you mean by "The data comes empty"?

What parts successfully run (try print statements) and which parts have unexpected behaviour. What is the behaviour?

ure is not directly equivalent to re, by the way, so figuring out if there are any requests, or any posted content, (without all the filtering/regex) would be a good beginning before coming up with patterns which ure CAN handle to filter stuff out.

Post Reply