The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages
> Python Programming
|
Making a Threaded HTTP Server
Discuss Making a Threaded HTTP Server in the Python Programming forum on Dev Shed. Making a Threaded HTTP Server Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

February 25th, 2004, 12:40 PM
|
|
Registered User
|
|
Join Date: Feb 2004
Posts: 1
Time spent in forums: < 1 sec
Reputation 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: URL
# 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.
|

February 28th, 2004, 01:03 PM
|
 |
Banned ;)
|
|
Join Date: Nov 2001
Location: Woodland Hills, Los Angeles County, California, USA
|
|
|
__________________
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
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|