Use Python to implement a simple HTTP server that can be uploaded and downloaded

Source: Internet
Author: User
This article mainly introduces how to use Python to implement a simple HTTP server capable of uploading and downloading. it is the basis for learning Python network programming. This example is implemented based on the Windows operating system, for more information, see

#! /Usr/bin/env python # coding = UTF-8 # modifyDate: 20120808 ~ 20120810 # Original Author: bones7456, http://li2z.cn/# Modified to: decli@qq.com # v1.2, changeLog: # +: file date/time/color display, multi-thread support, home page jump #-: solve the problem of garbled file names uploaded in different browsers: only IE, not processed by other browsers. #-: Some path display bugs, mainly cgi. escape () escape problems #?: Notepad ++ directly compiled server path problem "Introduction: This is a lightweight file sharing server written in python (based on the built-in SimpleHTTPServer module), supports file upload and download, if you have installed python (recommended version 2.6 ~ 2.7, does not support 3.x), and then go to the directory to be shared, execute: python SimpleHTTPServerWithUpload. py 1234, where 1234 is the port number specified for you, if not written, the default value is 8080 and then access http://localhost:1234 Yes. replace localhost or 1234 as appropriate. "Simple HTTP Server With Upload. this module builds on BaseHTTPServer by implementing the standard GETand HEAD requests in a fairly straightforward manner. "" _ version _ = "0.1" _ all _ = ["SimpleHTTPRequestHandler"] _ author _ = "bones7456" _ home_page _ = "" import OS, sys, zookeeper BaseHTTPServerfrom SocketServer import ThreadingMixInimport threadingimport urllib, export cgiimport into multiple reimport time try: from cStringIO import stringiow.t 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 [: 15]) [20:24]) class GetWanIp: def getip (self): try: myip = self. visit (" http://ip.taobao.com/service/getIpInfo.php?ip=myip ") Failed t: print" ip.taobao.com is Error "try: myip = self. visit (" http://www.bliao.com/ip.phtml ") Failed t: print" bliao.com is Error "try: myip = self. visit (" http://www.whereismyip.com/ ") Metadata T: # '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/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]) failed t Exception, e: print '--------> Warning: Port is not given, will use deafult port: 8080 'print '--------> if you want to use 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 '--------> 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' response> '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 modification_date (filename): # t = OS. path. getmtime (filename) # return datetime. datetime. fromtimestamp (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 from the current directory and any of its subdirectories. the MIME type for files is determined by calling. guess_type () method. and can reveive file uploaded by client. the GET/HEAD/POST requests are identical records t 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, 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 ("\ NUpload Result Page\ 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 (200) 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 B Oundary 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 out 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 ('Ut F-8 ') else: fn = OS. path. join (path, fn [0]) except T Exception, e: return (False, "Do not use Chinese characters for file names, or use IE to upload files with Chinese names. ") 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') handle t IOError: return (False, "Can't create file to write, do 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] out. write (preline) out. close () return (True, "File '% s' upload success! "% 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 has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which cas E the caller has 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 ("Location", self. path + "/") self. end_headers () return 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 mode. opening files in text mode may cause # newline translations, making the actual size of the content # transmitted * less * than the content-length! F = open (path, 'RB') handle T IOError: self. send_error (404, "File not found") return None self. send_response (200) self. send_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 is 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) does T OS. error: self. send_error (404, "No permission to list directory") return None list. sort (key = lambda a:. lower () f = StringIO () displaypath = cgi. escape (urllib. unquote (self. path) f. write ('') F. write ("\ NDirectory listing for % s\ N "% displaypath) f. write ("\ NDirectory listing for % s \ n "% displaypath) f. write (" \ n ")
    \ 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 (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. getcwd () + '/' + displaypath + displayname f. write (' \ N' % (urllib. quote (linkname), colorName, sizeof_fmt (OS. path. getsize (filename), modification_date (filename) f. write ("
    % S % S % S
    \ N\ N\ N ") length = f. tell () f. seek (0) self. send_response (200) 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/-separated 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 shocould proba Bly be diagnosed.) "# abandon query parameters path = path. split ('? ', 1) [0] path = path. split ('#', 1) [0] path = posixpath. normpath (urllib. 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. join (path, word) return path def copyfile (self, source, outputfile): "" Copy all data between two 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 object open for writing (or anything with a write () method ). the only reason for overriding this wocould be to change the block size or perhaps to replace newlines by CRLF -- note however that this 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-stream as a default; however it wocould 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_map [''] if not mimetypes. inited: mimetypes. init () # try to read system mime. types extensions_map = mimetypes. types_map.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 () # single thread # srvr = BaseHTTPServer. HTTPServer (serveraddr, SimpleHTTPRequestHandler) # multithreading srvr = ThreadingServer (serveraddr, SimpleHTTPRequestHandler) srvr. serve_forever ()

REF:

1. httpserver
========================================================
This httpserver is a enhanced version of SimpleHTTPServer.
It was 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 has more
Friendly error hit, and it can handle mimetype gracefully

Https://github.com/lerry/httpserver/blob/master/httpserver.py

2. SimpleHTTPServer based on java netty,

Because windows does not support some netty low-level APIs, this code can only run in linux:

Https://github.com/dvliman/SimpleHTTPServer

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.