python webserver, based on SimpleHTTPServer
1 #-*- coding:utf-8 -*- 2 #author: lichmama 3 #email: nextgodhand@163.com 4 #filename: httpd.py 5 import io 6 import os 7 import sys 8 import urllib 9 from BaseHTTPServer import HTTPServer 10 from SimpleHTTPServer import SimpleHTTPRequestHandler 11 12 class MyRequestHandler(SimpleHTTPRequestHandler): 13 protocol_version = "HTTP/1.1" 14 server_version = "PSHS/0.1" 15 sys_version = "Python/2.7.x" 16 target = "D:/web" 17 18 def do_GET(self): 19 if self.path == "/" or self.path == "/index": 20 content = open("signin.html", "rb").read() 21 self.send_head(content) 22 else: 23 path = self.translate_path(self.path) 24 if os.path.exists(path): 25 extn = os.path.splitext(path)[1].lower() 26 content = open(path, "rb").read() 27 self.send_head(content, type=self.extensions_map[extn]) 28 else: 29 content = open("404.html", "rb").read() 30 self.send_head(content, code=404) 31 self.send_content(content) 32 33 def do_POST(self): 34 if self.path == "/signin": 35 data = self.rfile.read(int(self.headers["content-length"])) 36 data = urllib.unquote(data) 37 data = self.parse_data(data) 38 try: 39 uid = data["uid"] 40 if uid != "": 41 content = open("success.html", "rb").read() 42 content = content.replace("$uid", uid) 43 self.send_head(content) 44 #do-something-in-backend 45 if not os.path.exists(self.target + "/" + uid): 46 os.mkdir(self.target + "/" + uid) 47 else: 48 content = "400, bad request." 49 self.send_head(content, code=400) 50 except KeyError: 51 content = "400, bad request." 52 self.send_head(content, code=400) 53 else: 54 content="403, forbiden." 55 self.send_head(content, code=403) 56 self.send_content(content) 57 58 def parse_data(self, data): 59 ranges = {} 60 for item in data.split("&"): 61 k, v = item.split("=") 62 ranges[k] = v 63 return ranges 64 65 def send_head(self, content, code=200, type="text/html"): 66 self.send_response(code) 67 self.send_header("Content-Type", type) 68 self.send_header("Content-Length", str(len(content))) 69 self.end_headers() 70 71 def send_content(self, content): 72 f = io.BytesIO() 73 f.write(content) 74 f.seek(0) 75 self.copyfile(f, self.wfile) 76 f.close() 77 78 if __name__ == "__main__": 79 if len(sys.argv) == 2: 80 #set the target where to mkdir, and default "D:/web" 81 MyRequestHandler.target = sys.argv[1] 82 try: 83 server = HTTPServer(("", 8080), MyRequestHandler) 84 print "pythonic-simple-http-server started, serving at http://localhost:8080" 85 server.serve_forever() 86 except KeyboardInterrupt: 87 server.socket.close()