1 #!/usr/bin/env python
2 #coding=utf-8
3
4 importos, sys, platform5 importposixpath6 importBaseHTTPServer7 from SocketServer importThreadingMixIn8 importthreading9 importurllib10 importcgi11 importshutil12 importmimetypes13 importre14 importtime15
16 try:17 from cStringIO importStringIO18 exceptImportError:19 from StringIO importStringIO20
21
22
23 #请求处理
24 classSimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):25
26 defdo_GET(self):27 #获取文件内容
28 f =None29 path =self.translate_path(self.path)30 ifos.path.isdir(path):31 if not self.path.endswith('/'):32 #redirect browser - doing basically what apache does
33 self.send_response(301)34 self.send_header("Location", self.path + "/")35 self.end_headers()36 returnNone37 try:38 f = open(path, 'rb')39 exceptIOError:40 self.send_error(404, "File not found")41 returnNone42 self.send_response(200)43 self.send_header("Content-type", "text/html")44 fs =os.fstat(f.fileno())45 self.send_header("Content-Length", str(fs[6]))46 self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))47 self.end_headers()48 shutil.copyfileobj(f,self.wfile)49 f.close()50
51 defdo_HEAD(self):52 """列出目录下的所有文件"""
53 path =self.translate_path(self.path)54 #获取路径下的文件列表
55 try:56 list =os.listdir(path)57 exceptos.error:58 self.send_error(404, "No permission to list directory")59 returnNone60 list.sort(key=lambdaa: a.lower())61 #print list
62 f =StringIO()63 displaypath =cgi.escape(urllib.unquote(self.path))64 for name inlist:65 fullname =os.path.join(path, name)66 f.write(fullname)67 f.write('\n')68 length =f.tell()69 f.seek(0)70 #发送response head
71 self.send_response(200)72 self.send_header("Content-type", "text/html")73 self.send_header("Content-Length", str(length))74 self.end_headers()75 #发送response data
76 shutil.copyfileobj(f,self.wfile)77
78 defdo_PUT(self):79 """Serve a POST request."""
80 r, info =self.put_file()81 print r, info, "by:", self.client_address82 f =StringIO()83 ifr:84 f.write("Success:")85 else:86 f.write("Failed:")87 f.write(info)88 length =f.tell()89 f.seek(0)90 self.send_response(200)91 self.send_header("Content-type", "text/html")92 self.send_header("Content-Length", str(length))93 self.end_headers()94 iff:95 shutil.copyfileobj(f, self.wfile)96 f.close()97
98
99 defput_file(self):100 #获取上传的内容
101 content = ""
102 remainbytes = int(self.headers['content-length'])103
104 line =self.rfile.readline()105 remainbytes -=len(line)106 content +=line107 while(remainbytes >0):108 line =self.rfile.readline()109 remainbytes -=len(line)110 content +=line111 #创建本地文件
112 savefilepath =self.translate_path(self.path)113 whileos.path.exists(savefilepath):114 savefilepath += "_"
115 try:116 out = open(savefilepath, 'wb')117 exceptIOError:118 return (False, "Can't create file to write, do you have permission to write?")119
120 remainbytes =len(content)121 out.write(content)122 return (True, "File %s upload success!" %savefilepath)123
124 deftranslate_path(self, path):125 path = path.split('?',1)[0]126 path = path.split('#',1)[0]127 path =posixpath.normpath(urllib.unquote(path))128 words = path.split('/')129 words =filter(None, words)130 path =os.getcwd()131 for word inwords:132 drive, word =os.path.splitdrive(word)133 head, word =os.path.split(word)134 if word in(os.curdir, os.pardir):135 continue
136 path =os.path.join(path, word)137 returnpath138
139 classThreadingServer(ThreadingMixIn, BaseHTTPServer.HTTPServer):140 pass
141
142 if __name__ == '__main__':143 #获取和解析port
144 try:145 port = int(sys.argv[1])146 exceptException, e:147 port = 8080
148 if not 1024 < port < 65535:149 port = 8080
150 serveraddr = ('', port)151 print 'listening on port: %d' %(port)152 #单线程
153 #srvr = BaseHTTPServer.HTTPServer(serveraddr, SimpleHTTPRequestHandler)
154 #多线程
155 srvr =ThreadingServer(serveraddr, SimpleHTTPRequestHandler)156 srvr.serve_forever()