Python implements a simple HTTP server that can upload and download

Source: Internet
Author: User
Tags datetime file upload http request join readline socket split port number

This article mainly introduces the use of Python to implement a simple upload download HTTP server, is the basis of Python network programming learning, this article is based on Windows operating system implementation, the need for friends can refer to the following

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30-31 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 The 96 97 98 99 100 101 102 103 104 105 106 107 108 109 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140-1 41 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170-171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201-2 02 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231-232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262-2 63 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298-299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329-3 30 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359-360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390-3 91 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 #!/usr/bin/env python #coding =utf-8 # modifydate:20120808 ~ 20120810 # Original Author: bones7456, http://li2z.cn/# Modified by: DECLI@QQ.C Om # v1.2,changelog: # +: File date/time/color display, multithreading support, home page Jump #-: Solve different browsers upload file name garbled problem: only IE, other browsers for the time being not processed. #-: Some paths show bugs, mostly Cgi.escape () escape problem #?: notepad++ directly compiled server path issues   "" Introduction: This is a python-written lightweight file Sharing server (based on the built-in Simpleh Ttpserver module), support file upload download, as long as you have installed Python (recommended version 2.6~2.7, do not support 3.x), and then go to the directory you want to share, execute: Python simplehttpserverwithupload.py 1234 1234 for you to specify the port number, if not write, the default is 8080 then access to http://localhost:1234, localhost or 1234, please replace as appropriate. ""   "" Simple HTTP Server with Upload.   This module builds on Basehttpserver by implementing the standard get and head requests in a fairly manner.   "" "  __version__ =" 0.1 "__all__ = [" Simplehttprequesthandler "] __author__ =" bones7456 "__home_page__ =" "& nbsp Import OS, sys, platform import posixpath import basehttpserver from socketserver import threadingmixin import Threading I Mport Urllib, URLLIB2 import CGI import sHutil Import mimetypes Import re import time   try:from Cstringio import Stringio except Importerror:from Stringio Import Stringio   def get_ip_address (ifname): Import socket import fcntl import struct s = Socket.socket (socket.af_in ET, Socket. SOCK_DGRAM) return Socket.inet_ntoa (Fcntl.ioctl (S.fileno (), 0x8915, # siocgifaddr struct.pack (' 256s ', ifname[:15])) [ 20:24])   class Getwanip:def GetIP (self): Try:myip = Self.visit ("http://ip.taobao.com/service/getIpInfo.php?ip= Myip ") Except:print" ip.taobao.com is Error "Try:myip = Self.visit (" http://www.bliao.com/ip.phtml ") 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.141 0.64 safari/537 ', # ' Referer ': ' Http://ip.taobaO.com/ipsearch.php ', # ' IP ': ' Myip ' #} #data = Urllib.urlencode (values) opener = Urllib2.urlopen (URL, None, 3) if url = = Opener.geturl (): str = Opener.read () return Re.search (' (d+.) {3}d+ ', str). Group (0)   def showtips (): print "print"--------------------------------------------------------- -------------->> ' try:port = Int (sys.argv[1]) except Exception, E:print '-------->> warning:port-not GI Ven, would use Deafult port:8080 ' print '-------->> if your want to the use of other port, please execute: ' print '------- ->> python simplehttpserverwithupload.py port ' print '-------->> port is a integer and it ' s range:1024 < Port < 65535 "Port = 8080   If not 1024 < port < 65535:port = 8080 # serveraddr = (', port) print '------ -->> now, listening at Port ' + str (port) + ' ... ' OSType = Platform.system () If OSType = "Linux": print '--------& Gt;> you can visit the url:http://' + Getwanip () getip () + ': ' +str (port) Else:print '-------->> You 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"% (nu M, ' TB ')   def modification_date (filename): # t = os.path.getmtime (filename) # return Datetime.datetime.fromtimestam P (t) return Time.strftime ("%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 to 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 are identical except 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, SELF.W) (). File F.close ()   def do_head (self): "" "Serve a head request." "" F = self.send_head () if F:f.close ()   def do_p OST (self): "" "Serve a POST request." "R, Info = Self.deal_post_data () print R, info," by: ", self.client_address f = stri Ngio () f.write (' <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 3.2 final//en" > "F.write (" <html>n<title>upload result page</ Title>n ") f.write (" <body>n<h2>upload result page</h2>n ") f.write (" <hr>n ") If R:f.write (" <strong>Success:</strong> ") else:f.write (" <strong>Failed:</strong> ") F.write (Info) F.write ("<br><a href="%s ">back</a>"% self.headers[' referer ']) f.write ("<hr><small> PoweRed by:bones7456, check new version at "F.write" ("<a href=" Http://li2z.cn/?s=SimpleHTTPServerWithUpload ">") F.write ("here</a>.</small></body>n</html>n") length = F.tell () f.seek (0) Self.send_response (m) 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[' content-length ']) line = Self.rfile.readline () remainbytes-= Len (line) If not boundary in Line:return (False, [Content not begin with boundary] line = Self.rfile.readline () remainbytes = Len (line) fn = Re.findall (R ' content-disposition.*name= "file"; filename= "(. *)" ', line) if not Fn:return (False, "Can" t find O UT file name ... "path = Self.translate_path (self.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, "file name 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) = Self.rfile.readline () Remainbytes = Len (line) try:out = open (FN, ' WB ') except Ioerror:return (False, "Can" t create file to write, does you have Permission to write? ")   Preline = Self.rfile.readline () remainbytes = Len (preline) while remainbytes > 0:line = Self.rfile.readline () Remainbytes = Len (line) if boundary in line:preline = preline[0:-1] If Preline.endswith (' R '): Preline = preline[0:-1] ou T.write (Preline) out.close () (True, "File '%s ' upload success!"% fn) Else:out.write (preline) Preline = line Retur N (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 are either a file object (which has to being copied to the outputfile by the caller unless the COmmand is head, and must is closed by the caller under all circumstances), or None, in which case the caller Further to do.   "" "Path = Self.translate_path (self.path) f = None if Os.path.isdir (path): If not self.path.endswith ('/'): # Redire CT browser-doing basically what Apache does Self.send_response ("Self.send_header", Location + "/") Self.path Nd_headers () return is None for index in "index.html", "index.htm": index = os.path.join (path, index) if os.path.exists (index ): Path = index break Else:return self.list_directory (path) CType = self.guess_type (path) Try: # Always read in binary mo De. Opening files in text mode may cause # newline translations, making the actual size of the content # transmitted *less* th An The content-length! f = open (path, ' RB ') except IOError:self.send_error (404, "File not Found") return to None Self.send_response Header ("Content-type", ctype) fs = Os.fstat (F.fileno ()) Self.send_header ("Content-length", str (FS[6))) sElf.send_header ("Last-modified", Self.date_time_string (Fs.st_mtime)) self.end_headers () return f   def List_ Directory (self, Path): "" "Helper to produce a directory listing (absent index.html).   Return value are either a file object, or None (indicating an error). In either case, the headers are 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 no Ne list.sort (key=lambda a:a.lower ()) F = Stringio () Displaypath = Cgi.escape (Urllib.unquote (Self.path)) F.write (' <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 3.2 final//en" > "F.write (" <html>n<title>directory listing for%s& Lt;/title>n "% Displaypath) f.write (" <body>n<h2>directory listing for%s</h2>n "% Displaypath) F.write ("<hr>n") f.write ("<form enctype=" Multipart/form-data "method=" post ">") f.write ("<input name= "File" type= "file"/> ") f.write (" <input tyPe= "Submit" value= "Upload"/> ") F.write (" ") F.write (" <input type= "button" value= "" homepage "onclick=" location= "/ ' > ') f.write ("</form>n") f.write ("<hr>n<ul>n") for name in List:fullname = Os.path.join (Path, Name) ColorName = displayname = linkname = name # append/for directories or @ for symbolic links if Os.path.isdir (Fullna Me): colorname = ' <span style= ' background-color: #CEFFCE; > ' + name + '/</span> ' displayname = name linkname = name + '/' if Os.path.islink (fullname): colorname = ' <spa N style= "Background-color: #FFBFFF;" > ' + name + ' @</span> ' displayname = name # NOTE:A link to a directory displays with @ and links with/filename = OS.GETCWD () + '/' + Displaypath + displayname f.write (' <table><tr><td width= ' 60%% ' ><a href= '%s ' &G T;%S</A></TD><TD width= "20%%" >%s</td><td width= "20%%"% ( Urllib.quote (linkname), ColorName, Sizeof_fmt (Os.path.getsize (FilenaMe), modification_date (filename)) f.write ("</table>n<hr>n</body>n</html>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):" "" Translate a/-separat Ed PATH to the local filename syntax.   Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.)   "" # Abandon query parameters Path = Path.split ('? ', 1) [0] path = path.split (' # ', 1) [0] path = Posixpath.normpath (ur Llib.unquote (path)) words = Path.split ('/') words = filter (None, words) path = OS.GETCWD () for word in words:drive, Word = Os.path.splitdrive (Word) head, Word = os.path.split (word) if Word in (Os.curdir, Os.pardir): Continue path = Os.path.joi N (path, Word) return to path   def copyfile (self, Source, outputfile): "" "Copy all data between two FIle objects.   The SOURCE argument is a file object open to reading (or anything with a read () method) and the destination Argume NT is a file object open to writing (or anything with a write () method).   The only reason for overriding this would is to change the blocks size or perhaps to replace newlines by CRLF- E However that this is the default server uses this to copy binary data as.   "" "Shutil.copyfileobj (source, outputfile)   def guess_type (self, Path):" "Guess the type of a file.   Argument is a PATH (a filename).   return value are 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- Stream as a default; However it would be 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_m Ap[']   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/plain ', '. H ': ' Text/plain ',})   class Threadingserver (ThreadingMixIn, basehttpserver.httpserver): Pass   def test ( Handlerclass = Simplehttprequesthandler, ServerClass = basehttpserver.httpserver): Basehttpserver.test (HandlerClass, ServerClass)   If __name__ = = ' __main__ ': # test ()   #单线程 # srvr = Basehttpserver.httpserver (serveraddr, Simpleh Ttprequesthandler)   #多线程 srvr = Threadingserver (serveraddr, Simplehttprequesthandler)   Srvr.serve_forever ( )

REF:

1, Httpserver

=======================================

This httpserver is a enhanced version of Simplehttpserver.

It is write in Python, I with some code from Bottle[https://github.com/defnull/bottle]

IT support resuming download, you can set the document root, it has 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

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.