Hi,
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
Retrieve values from HTML Form
-
- Posts: 463
- Joined: Wed Apr 08, 2015 5:19 am
Re: Retrieve values from HTML Form
The form values will be in the body of the request. AFAICS you are reading only the headers plus up to 512 bytes (but probably less). Also, you are mixing str with bytes, since client.recv() returns bytes, but you are comparing to with a str object ("\r\n\r\n"). This works in MicroPython, but not in CPython and is bad practice. Your code would be much clearer, if you decoded the request from bytes to string in one place (e.g. directly after your while loop).stan92 wrote: ↑Sun Nov 05, 2017 2:13 pmCode: Select all
request = b"" try: while not "\r\n\r\n" in request: request += client.recv(512) except OSError: pass