I am trying to build a simple web server, that receives GPS coordinates through POST requests and then shows them on a webpage. I receive just fine the coordinates from my phone, it prints them to the server window so i understand that the variables 'lat' and 'lon' should have been updated with the actual coordinates, but when i open my browser i only get "test test".. Sorry for my noob question, but I am very new to python and I cannot understand why the class MyHandler can't access the variables.. This is my code so far:
PORT = 5050
lat="test"
lon="test"
speed="test"
def serv_responseGET(s):
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
s.wfile.write(lat, lon)
def serv_responsePOST(s):
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
s.wfile.write(' ');
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(s):
print s.path
length = int(s.headers['Content-Length'])
post_data = urlparse.parse_qs(s.rfile.read(length).decode('utf-8'))
for key, value in post_data.iteritems():
if key=="lat":
lat=''.join(value)
if key=="lon":
lon=''.join(value)
if key=="speed":
speed=''.join(value)
print datetime.datetime.now()
print "lat=", lat
print "lon=", lon
print "spd=", speed
serv_responsePOST(s)
def do_GET(s):
print s.path
serv_responseGET(s)
if __name__ == '__main__':
server_class = BaseHTTPServer.HTTPServer
httpd = server_class(('', PORT), MyHandler)
print time.asctime(), "Server Starts - %s:%s" % ('', PORT)
httpd.serve_forever()
and this is what i get on python window after a POST from my phone:
/
2014-10-25 16:23:20.598733
lat= 37.971649
lon= 23.727053
spd= 0.0
192.168.2.50 - - [25/Oct/2014 16:23:20] "POST / HTTP/1.1" 200 -
In Python, when you assign to a variable inside a procedure, it assumes you meant to create a local variable and ignores the global variables. To assign to global variables, you need to declare them first. so just add the line
global lat, lon, speed
To the start of your do_POST and I believe that will fix it.