#!/usr/bin/env python#coding=utf-8# modifydate:20120808 ~ 20120810# Original Author: bones7456, http://li2z.cn/# Modified by: decli@qq.com# v1.2,changelog:# +: File date/time/color display, multi-threaded support, home page Jump #-: Solve the different browser upload file name garbled problem: only IE, other browsers temporarily did not deal with. #-: Some paths show bugs, mostly Cgi.escape () escape problem #?: Server path problem directly compiled under notepad++ "" "Introduction: This is a python-written lightweight file Sharing server (based on the built-in Simplehttpserv ER module), support file upload download, as long as you install Python (recommended version 2.6~2.7, does not support 3.x), and then go to the directory you want to share, execute: Python simplehttpserverwithupload.py 1234 where 1 234 for the port number you specified, such as do not write, the default is 8080 and then access http://localhost:1234, localhost or 1234, please replace as appropriate. "" "" "Simple HTTP Server with Upload. This module, builds on Basehttpserver by implementing, Getand HEAD requests in a fairly straightforward manner. "" "__version__ =" 0.1 "__all__ = [" Simplehttprequesthandler "]__author__ =" bones7456 "__home_page__ =" "Import OS, sys, p Latformimport posixpathimport basehttpserverfrom socketserver import threadingmixinimport threadingimport urllib, Urllib2import cgiimport shutilimport mimetypesimport reimport time Try:from Cstringio Import stringioexcept importerror:from stringio import Stringio def get_ip_address (ifname): Import socket Import fcntl import struct s = socket.socket (socket.af_inet, socket. SOCK_DGRAM) return Socket.inet_ntoa (Fcntl.ioctl (S.fileno (), 0x8915, # siocgifaddr struct.pack (' 256s ', ifname[:1 5])) [20:24]) class Getwanip:def getip (self): Try:myip = Self.visit ("http://ip.taobao.com/service/getIpInfo.ph P?ip=myip ") Except:print" ip.taobao.com is Error "Try:myip = Self.visit (" Http://www.bliao.com/ip.pht ML ") except:print" bliao.com is Error "Try:myip = Self.visit (" http://www.whereismyip.com/") Except: # ' Nonetype ' object has no attribute ' group ' print ' Whereismyip is Error ' Myip = ' 127.0.0 .1 "Return Myip def Visit (self,url): #req = Urllib2. Request (URL) #values = {' user-agent ': ' mozilla/5.0 (Windows NT 6.1) applewebkit/537.31 (khtml, like Gecko) chrome/26.0. 1410.64 SAFARI/5PNs ', # ' Referer ': ' http://ip.taobao.com/ipSearch.php ', # ' IP ': ' Myip ' #} #data = Urllib.urlenco De (values) opener = Urllib2.urlopen (URL, None, 3) If url = = Opener.geturl (): str = Opener.read () return RE.S Earch (' (\d+\.) {3}\d+ ', str). Group (0) def showtips (): print "print"-------------------------------------------------------------- --------->> ' try:port = Int (sys.argv[1]) except Exception, E:print '-------->> warning:port is no T given, would use Deafult port:8080 ' print '-------->> if you want to use other ports, please execute: ' Prin T '-------->> python simplehttpserverwithupload.py port ' print '-------->> port is a integer and it ' s rang e:1024 < Port < 65535 "Port = 8080 If not 1024x768 < port < 65535:port = 8080 # serveraddr = (", port) print '-------->> now, listening at Port ' + str (port) + ' ... ' OsType = Platform.system () if OsType = = "Linux": print '-------->> You can visit the url:http://' + Getwanip (). GetIP () + ': ' +str (port) else:print '-------->> Can visit the url:http://127.0.0.1: ' +str (port) print '------------------------------------------------------------- ---------->> ' print ' "return (', port) serveraddr = Showtips () def sizeof_fmt (num): For x in [' bytes ', ' KB ', ' MB ', ' GB ']: if num < 1024.0:return "%3.1f%s"% (num, x) num/= 1024.0 return "%3.1f%s"% (num, ' TB ') def mo Dification_date (filename): # t = os.path.getmtime (filename) # return Datetime.datetime.fromtimestamp (t) return TIME.STR Ftime ("%y-%m-%d%h:%m:%s", Time.localtime (os.path.getmtime (filename)) class Simplehttprequesthandler ( Basehttpserver.basehttprequesthandler): "" Simple HTTP Request handler with Get/head/post commands. This serves files from the current directory and any of its subdirectories. The MIME type for files are determined by calling the. Guess_type () method. And can reveive file uploaded by Client. The Get/head/post requests is identical except that the HEAD request omits the actual contents of the file. "" "Server_version =" simplehttpwithupload/"+ __version__ def do_get (self):" "" Serve a GET request. "" " # print "...", Threading.currentthread (). GetName () F = self.send_head () if F:self.copyfile (f), the "." Self.wfile) F.close () def do_head (self): "" "Serve a HEAD request." " f = self.send_head () if F:f.close () def do_post (self): "" "Serve a POST request." " R, Info = Self.deal_post_data () print R, info, "by:", self.client_address f = Stringio () f.write ('') F.write ("\ n<title>Upload Result Page</title>\ n ") F.write ("\ nUpload Result Page
\ n ") f.write (" \ n ") if R:f.write ("Success:") Else:f.write ("Failed:") F.write (Info) f.write ("
Back "% self.headers[' referer ']) f.write ("Powered by:bones7456, check new version at ") F.write (" ") F.write (" here.\ n\ n ") length = F.tell () f.seek (0) self.send_response (+) Self.send_header (" Content-type "," text/html ") self . Send_header ("Content-length", str (Length)) self.end_headers () if F:self.copyfile (f, self.wfile) F.close ( ) def deal_post_data (self): boundary = self.headers.plisttext.split ("=") [1] remainbytes = Int (self.headers[' Co Ntent-length ']) line = Self.rfile.readline () remainbytes-= Len (line) if not boundary in Line:return (False , "Content not to begin with boundary") line = Self.rfile.readline () remainbytes-= Len (line) fn = Re.findall (R ' Cont Ent-disposition.*name= "File"; Filename= "(. *)" ', line] if not Fn:return (False, "Can ' t find out file name ...") path = Self.translate_path (sel F.path) OsType = Platform.system () try:if OsType = = "Linux": fn = os.path.join (path, Fn[0].decode (' GBK ') ). Encode (' Utf-8 ')) ELSE:FN = Os.path.join (path, fn[0]) except Exception, E:return (False, "textName please do not use Chinese, or use IE to upload Chinese name files. ") while Os.path.exists (FN): fn + =" _ "line = Self.rfile.readline () remainbytes-= Len (line), line = self. Rfile.readline () Remainbytes-= Len (line) try:out = open (FN, ' WB ') except Ioerror:return (False, "Can ' t create file to write, does permission to write? ") Preline = Self.rfile.readline () remainbytes-= Len (preline) while remainbytes > 0:line = Self.rfile.readlin E () Remainbytes-= Len (line) if boundary in line:preline = preline[0:-1] if Preline.endswith (' \ R ' ): Preline = preline[0:-1] Out.write (preline) Out.close () return (True, "File '%s ' upload su ccess! "% fn" Else:out.write (preline) Preline = line return (False, "Unexpect Ends of data.") def send_head (self): "" "Common Code for GET and head commands. This sends the response code and MIME headers. Return value is either a file object (which have to beCopied to the outputfile by the caller unless the command is HEAD, and must is closed by the caller under all Circu mstances), or None, in which case the caller have nothing further to do. "" "Path = Self.translate_path (self.path) f = None if Os.path.isdir (path): If not self.path.endswith ('/'): # REDIRECT Browser-doing basically what Apache does Self.send_response (301) self.send_header ("Locati On ", Self.path +"/") Self.end_headers () return None for index in" index.html "," index.htm ": IND ex = Os.path.join (path, index) if os.path.exists (index): path = index break Else:ret Urn Self.list_directory (path) CType = self.guess_type (path) Try: # always read in binary mode. Opening files in text mode cause # newline translations, making the actual size of the content # transmitted *less* than the content-length! f = open (path, ' RB ') except IOError:Self.send_error (404, "File not Found") return None self.send_response ("Self.send_header" Content-type PE) FS = Os.fstat (F.fileno ()) Self.send_header ("Content-length", str (fs[6])) Self.send_header ("last-modified", SE Lf.date_time_string (Fs.st_mtime)) self.end_headers () return F def list_directory (self, Path): "" "Helper to Prod UCE a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers is sent, making the interface the same as for Send_head (). "" "Try:list = Os.listdir (path) except Os.error:self.send_error (404," No permission to list directory ") Return None List.sort (Key=lambda a:a.lower ()) F = Stringio () Displaypath = Cgi.escape (Urllib.unquote (SELF.P ATH)) F.write ('') F.write ("\ n<title>Directory Listing for%s</title>\ n "% Displaypath) f.write ("\ nDirectory Listing for%s
\ n "% Displaypath) f.write (" \ n ") f.write (" \ n ") f.write (" \ n
\ n ") for name in List:fullname = Os.path.join (path, name) ColorName = displayname = linkname = name # A Ppend/for directories or @ for symbolic links if Os.path.isdir (fullname): ColorName = '
' + name + '/' displayname = name linkname = name + "/" if Os.path.islink (fullname): ColorName = '
' + name + ' @' displayname = name # NOTE:A link to a directory displays with @ and links with/filename = OS.GETCW D () + '/' + Displaypath + displayname f.write ('
%s |
%s |
%s |
\ n '% (Urllib.quote (linkname), ColorName, sizeof_fmt (os.path.getsize (filename)), Modification_date (fi Lename)) F.write ("
\ n\ n\ n ") length = F.tell () f.seek (0) self.send_response (+) Self.send_header (" Content-type "," text/html ") self . Send_header ("Content-length", str (Length)) self.end_headers () return F def translate_path (self, Path): "" "Tran Slate a/-separated PATH to the local filename syntax. Components: Mean special things to the local file system (e.g. drive or directory names) is ignored. (XXX they should probably be diagnosed.) "" "# Abandon query parameters Path = Path.split ('? ', 1) [0] path = path.split (' # ', 1) [0] path = Posixpath.normpa Th (Urllib.unquote (path)) words = Path.split ('/') words = filter (None, words) path = OS.GETCWD () for word in Wo rds:drive, Word = os.path.splitdrive (word) head, Word = os.path.split (word) if Word in (Os.curdir, Os.pard IR): Continue path = os.path.join (path, Word) return path def copyfile (self, Source, outputfile): "" "Copy All Data between the file objects. The SOURCE ArgumENT is a file object open for reading (or anything with a read () method) and the DESTINATION argument is a file obje CT open for writing (or anything with a write () method). The only reason for overriding this would is to change the block size or perhaps to replace newlines by CRLF--note However that this is the default server uses this to copy binary data as well. "" "Shutil.copyfileobj (source, outputfile) def guess_type (self, Path):" "" Guess the type of a file. Argument is a PATH (a filename). Return value is a string of the form Type/subtype, usable for a MIME Content-type header. The default implementation looks the file ' s extension up in the table Self.extensions_map, using Application/octet-stre Am as a default; However it would is permissible (if slow) to look inside the data to make a better guess. "" "Base, ext = Posixpath.splitext (path) if ext in Self.extensions_map:return self.extensions_map[ext] Ext= Ext.lower () if ext in Self.extensions_map:return Self.extensions_map[ext] Else:return self.extensions_ map["] if not mimetypes.inited:mimetypes.init () # try to read system mime.types Extensions_map = Mimetypes.types_m Ap.copy () extensions_map.update ({": ' Application/octet-stream ', # Default '. Py ': ' Text/plain ', '. C ': ' Text/pla In ', '. h ': ' Text/plain ',}) class Threadingserver (ThreadingMixIn, Basehttpserver.httpserver): Pass def Test (Handl Erclass = Simplehttprequesthandler, ServerClass = basehttpserver.httpserver): Basehttpserver.test (HandlerClass, Serve Rclass) If __name__ = = ' __main__ ': # Test () #单线程 # srvr = Basehttpserver.httpserver (serveraddr, Simplehttprequesthan dler) #多线程 srvr = Threadingserver (serveraddr, Simplehttprequesthandler) Srvr.serve_forever ()
REF:
1, Httpserver
=======================================
This httpserver is a enhanced version of Simplehttpserver.
It is write in Python, I use some code from Bottle[https://github.com/defnull/bottle]
IT support resuming download, you can set the document root, it had more
Friendly error hit, and it can handle mimetype gracefully
https://github.com/lerry/httpserver/blob/master/httpserver.py
2, based on the Java Netty Simplehttpserver,
Because Windows does not support some Netty low-level APIs, the code can only run under Linux:
Https://github.com/dvliman/SimpleHTTPServer