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 32 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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | #!/usr/bin/python
import time
import BaseHTTPServer
from pprint import pprint
import urlparse
HOST_NAME = 'localhost'
PORT_NUMBER = 8000
class MyHandler( BaseHTTPServer.BaseHTTPRequestHandler ):
def get_request_info( self ):
parsed_path = urlparse.urlparse( self.path )
request_dictionary = dict()
request_dictionary[ 'raw_requestline' ] = str( self.raw_requestline )
request_dictionary[ 'client_address' ] = str( self.client_address )
request_dictionary[ 'client_name_lookup' ] = str( self.address_string() )
request_dictionary[ 'command' ] = str( self.command )
request_dictionary[ 'path' ] = str( self.path )
request_dictionary[ 'request_version' ] = str( self.request_version )
request_dictionary[ 'parsed_path' ] = parsed_path.path
request_dictionary[ 'parsed_path_query' ] = parsed_path.query
request_dictionary[ 'server_version' ] = str( self.server_version )
request_dictionary[ 'server_sys_version' ] = str( self.sys_version )
request_dictionary[ 'server_protocol_version' ] = str( self.protocol_version )
return request_dictionary
def send_headers( self , content_type ): # TODO: add a variable to modify content type
self.send_response( 200 )
self.send_header( 'Content-type' , content_type )
# self.send_header( "Content-length" , len( RESPONSE ) )
self.end_headers()
def do_HEAD( self ):
self.send_headers( 'text/plain' )
def do_GET( self ):
request_dictionary = self.get_request_info()
print '%s \n' % ( request_dictionary )
self.send_headers( 'text/plain' )
self.wfile.write( '%s' % ( request_dictionary) )
pprint( vars( self ) )
def do_POST( self ):
request_dictionary = self.get_request_info()
print '%s \n' % ( request_dictionary )
self.send_headers( 'text/plain' )
self.wfile.write( '%s' % ( request_dictionary) )
pprint (vars(self))
# pprint (vars(self.connection))
# pprint (vars(self.headers))
# pprint (vars(self.request))
# pprint (vars(self.rfile))
# pprint (vars(self.server))
# pprint (vars(self.wfile))
# pprint (vars(self.fp))
# request_dictionary[ 'user-agent' ] = str( self.headers[ 'user-agent' ] )
# request_dictionary[ 'content-type' ] = str( self.headers[ 'Content-Type' ] )
# length = int( self.headers[ 'Content-Length' ] )
# if length > 0:
# post_data = urlparse.parse_qs( self.rfile.read( length ).decode('utf-8') )
# for key, value in post_data.iteritems():
# print "%s=%s" % ( key , value )
if __name__ == '__main__':
server_class = BaseHTTPServer.HTTPServer
httpd = server_class( ( HOST_NAME , PORT_NUMBER ), MyHandler )
print time.asctime(), "Server Starts - %s:%s" % ( HOST_NAME , PORT_NUMBER )
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % ( HOST_NAME , PORT_NUMBER )
|