#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2004
    Posts
    1
    Rep Power
    0

    Making a Threaded HTTP Server


    How do I make the following a threaded HTTP Server?

    Code:
    import sys, os, posixpath
    from Cookie import Cookie
    import BaseHTTPServer, urllib
    
    
    PORT = 8888
    
    
    class RequestHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    
       server_version = "RequestServer/1.0"
    
       def do_GET(self):
          self._get_request()
          self.send_head()
          self.wfile.write("Your request has been logged. Thank you. Goodbye.")
    
       def do_HEAD(self):
          self._get_request()
          self.send_head()
    
       def do_POST(self):
          script, env = self.prepare_cgi_env()
          form = self.get_form(env)
          self._get_request()
          self.server.request += str(form)
          self.send_head()
    
       def translate_path(self, path):
          # Copied from SimpleHTTPServer.py
          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 prepare_cgi_env(self):
          # Copied from CGIHTTPServer.py
          rest = self.path[len("/cgi-bin/"):]
          i = rest.rfind('?')
          if i >= 0:
             rest, query = rest[:i], rest[i+1:]
          else:
             query = ''
          #i = rest.find('/') # for PATH_INFO
          #if i >= 0:
          #   script, rest = rest[:i], rest[i:]
          #else:
          #   script, rest = rest, ''
          script = rest
          rest = ''
          scriptname = "/cgi-bin/" + script
    
          # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
          # XXX Much of the following could be prepared ahead of time!
          env = {}
          env['SERVER_SOFTWARE'] = self.version_string()
          env['SERVER_NAME'] = self.server.server_name
          env['GATEWAY_INTERFACE'] = 'CGI/1.1'
          env['SERVER_PROTOCOL'] = self.protocol_version
          env['SERVER_PORT'] = str(self.server.server_port)
          env['REQUEST_METHOD'] = self.command
          uqrest = urllib.unquote(rest)
          env['PATH_INFO'] = uqrest
          env['PATH_TRANSLATED'] = self.translate_path(uqrest)
          env['SCRIPT_NAME'] = scriptname
          if query:
             env['QUERY_STRING'] = query
          host = self.address_string()
          if host != self.client_address[0]:
             env['REMOTE_HOST'] = host
          env['REMOTE_ADDR'] = self.client_address[0]
          authorization = self.headers.getheader("authorization")
          if authorization:
             authorization = authorization.split()
             if len(authorization) == 2:
                import base64, binascii
                env['AUTH_TYPE'] = authorization[0]
                if authorization[0].lower() == "basic":
                   try:
                      authorization = base64.decodestring(authorization[1])
                   except binascii.Error:
                      pass
                   else:
                      authorization = authorization.split(':')
                      if len(authorization) == 2:
                         env['REMOTE_USER'] = authorization[0]
          # XXX REMOTE_IDENT
          if self.headers.typeheader is None:
             env['CONTENT_TYPE'] = self.headers.type
          else:
             env['CONTENT_TYPE'] = self.headers.typeheader
          length = self.headers.getheader('content-length')
          if length:
             env['CONTENT_LENGTH'] = length
          accept = []
          for line in self.headers.getallmatchingheaders('accept'):
             if line[:1] in "\t\n\r ":
                accept.append(line.strip())
             else:
                accept = accept + line[7:].split(',')
          env['HTTP_ACCEPT'] = ','.join(accept)
          ua = self.headers.getheader('user-agent')
          if ua:
             env['HTTP_USER_AGENT'] = ua
    
          co = filter(None, self.headers.getheaders('cookie'))
          if co:
             env['HTTP_COOKIE'] = cookie = ', '.join(co)
             self.cookie = Cookie(cookie)
    
          #os.environ.update(env)
          #decoded_query = query.replace('+', ' ')
    
          return script, env
    
       def get_form(self, env):
          import cgi
          headers=self.headers
          headers['content-type'] = 'application/x-www-form-urlencoded'
          return cgi.FieldStorage(fp=self.rfile, headers=headers, environ=env)
    
       def send_head(self):
          self.send_response(303)
          self.send_header("Content-Type", "text/html")
          self.send_header("Location", "http://localhost")
          self.end_headers()
    
    
       def _get_request(self):
          host, port = self.client_address
          print "Connected by", host, port
    
          # get data
          self.server.request = self.raw_requestline + str(self.headers)
    
    
    def main():
       # get port
       if len(sys.argv) > 1:
          port = int(eval(sys.argv[1]))
       else:
          port = PORT
    
       print "Waiting..."
       server = BaseHTTPServer.HTTPServer(('', port), RequestHTTPRequestHandler)
       server.handle_request() # do not server forever - serve just 1 request
    
       # store to file
       outfile = open("request.txt", 'w')
       outfile.write(server.request)
       outfile.close()
    
       print "Done."
    
    main()
    Last edited by netytan; February 25th, 2004 at 03:49 PM.
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,625
    Rep Power
    4247
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo

IMN logo majestic logo threadwatch logo seochat tools logo