Simple webserver in python

Ok, all this code is somewhere on the web, but at least I will know how to find it again….

It shows how to:

The code is dirty and was extracted from the app I already wrote, trying to remove irrelevant stuff. The HTML in particular are just bits, and do not produce valid HTML pages. But you get the idea.

 1 import cgi
 2 import Cookie
 3 import sys
 4 from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
 5 
 6 class MainHandler(BaseHTTPRequestHandler):
 7   def do_GET(self):
 8     if self.path=='/favicon.ico':
 9       return
10     p = self.path.split("?")
11     path = p[0][1:].split("/")
12     params = {}
13     if len(p) > 1:
14       params = cgi.parse_qs(p[1], True, True)
15     # do stuff...
16 
17   def do_POST(self):
18     # Pretty much the same as do_READ()
19     # call WriteCookie() or DoSomethingWithUploadedFile()...
20     # other stuff....
21 
22   def DoSomethingWithUploadedFile(self, groupId):
23     ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
24     query = cgi.parse_multipart(self.rfile, pdict)
25     self.send_response(200)
26     self.end_headers()
27     fileContent = query.get('file')[0]
28     # do something with fileContent
29     self.wfile.write("POST OK.");
30 
31   def RedirectTo(self, url, timeout=0):
32     self.wfile.write("""<html><head>
33       <meta HTTP-EQUIV="REFRESH"
34             content="%i; url=%s"/></head>""" % (timeout, url))
35 
36   def WriteCookie(self):
37     # Shows how to read form values from a POST request
38     # and write a cookie with a value from the form
39     form = cgi.FieldStorage(headers=self.headers, fp=self.rfile,
40     environ={'REQUEST_METHOD':'POST',
41              'CONTENT_TYPE':self.headers['Content-Type']})
42 
43     val = form.getfirst('myvalue', None)
44     self.send_response(200)
45     self.send_header('Content-type', 'text/html')
46     if val:
47       c = Cookie.SimpleCookie()
48       c['value'] = val
49       self.send_header('Set-Cookie', c.output(header=''))
50       self.end_headers()
51       self.RedirectTo(form.getfirst('follow', '/'))
52     else:
53       self.end_headers()
54       self.wfile.write("No username ?")
55 
56   def ReadCookie(self):
57     if "Cookie" in self.headers:
58       c = Cookie.SimpleCookie(self.headers["Cookie"])
59       return c['value'].value
60     return None
61 
62 def main(port):
63   try:
64     server = HTTPServer(('', int(port)), MainHandler)
65     print 'started httpserver...'
66     server.serve_forever()
67   except KeyboardInterrupt:
68     print '^C received, shutting down server'
69     server.socket.close()
70 
71 if __name__ == '__main__':
72   main(sys.argv[1])
Read GPS logs from QStarz data logger » « Pdf To Odp