1 #-*-coding:utf-8-*-2 #Author:lichmama3 #Email: [Email protected]4 #filename:httpd.py5 Importio6 ImportOS7 ImportSYS8 ImportUrllib9 fromBasehttpserverImportHttpserverTen fromSimplehttpserverImportSimplehttprequesthandler One A classMyrequesthandler (simplehttprequesthandler): -Protocol_version ="http/1.1" -Server_version ="pshs/0.1" theSys_version ="python/2.7.x" -target ="D:/web" - - defDo_get (self): + ifSelf.path = ="/" orSelf.path = ="/index": -Content = Open ("signin.html","RB"). Read () + self.send_head (content) A Else: atPath =Self.translate_path (Self.path) - ifos.path.exists (path): -Extn = os.path.splitext (path) [1].lower () -Content = open (path,"RB"). Read () -Self.send_head (Content, type=Self.extensions_map[extn]) - Else: inContent = Open ("404.html","RB"). Read () -Self.send_head (Content, code=404) to self.send_content (content) + - defDo_post (self): the ifSelf.path = ="/signin": *data = self.rfile.read (int (self.headers["Content-length"])) $data =urllib.unquote (data)Panax Notoginsengdata =self.parse_data (data) - Try: theUID = data["UID"] + ifUID! ="": AContent = Open ("success.html","RB"). Read () theContent = Content.replace ("$uid", UID) + self.send_head (content) - #Do-something-in-backend $ if notOs.path.exists (Self.target +"/"+uid): $Os.mkdir (Self.target +"/"+uid) - Else: -Content ="the bad request." theSelf.send_head (Content, code=400) - exceptKeyerror:WuyiContent ="the bad request." theSelf.send_head (Content, code=400) - Else: WuContent="403, Forbiden." -Self.send_head (Content, code=403) About self.send_content (content) $ - defParse_data (self, data): -Ranges = {} - forIteminchData.split ("&"): AK, V = item.split ("=") +RANGES[K] =v the returnRanges - $ defSend_head (self, content, code=200, type="text/html"): the self.send_response (code) theSelf.send_header ("Content-type", type) theSelf.send_header ("Content-length", str (content) ) the self.end_headers () - in defsend_content (self, content): thef =io. Bytesio () the f.write (content) About f.seek (0) the Self.copyfile (F, Self.wfile) the f.close () the + if __name__=="__main__": - ifLen (sys.argv) = = 2: the #set the target where to mkdir, and default "D:/web"BayiMyrequesthandler.target = sys.argv[1] the Try: theServer = Httpserver (("", 8080), Myrequesthandler) - Print "Pythonic-simple-http-server started, serving at http://localhost:8080" - Server.serve_forever () the exceptKeyboardinterrupt: theServer.socket.close ()
Python webserver, based on Simplehttpserver