#!/usr/bin/python
import time
import errno
"""HTTP client class borrowed from the httplib.py
See the following URL for a description of the HTTP/1.0 protocol:
http://www.w3.org/hypertext/WWW/Protocols/
(I actually implemented it from a much earlier draft.)
Example:
>>> from httplib import HTTP
>>> h = HTTP('www.python.org')
>>> h.putrequest('GET', '/index.html')
>>> h.putheader('Accept', 'text/html')
>>> h.putheader('Accept', 'text/plain')
>>> h.endheaders()
>>> errcode, errmsg, headers = h.getreply()
>>> if errcode == 200:
... f = h.getfile()
... print f.read() # Print the raw HTML
...
Python Language Home Page
[...many more lines...]
>>>
Note that an HTTP object is used for a single request -- to issue a
second request to the same server, you create a new HTTP object.
(This is in accordance with the protocol, which uses a new TCP
connection for each request.)
"""
import socket
import select
import string
import mimetools
HTTP_VERSION = 'HTTP/1.0'
HTTP_PORT = 80
DelaySecs = 2
DumpData = None
class HTTP:
"""This class manages a connection to an HTTP server."""
def __init__(self, host = '', port = 0):
"""Initialize a new instance.
If specified, `host' is the name of the remote host to which
to connect. If specified, `port' specifies the port to which
to connect. By default, httplib.HTTP_PORT is used.
"""
self.debuglevel = 0
self.file = None
self.valid = None
self.metaHeader = ''
if host:
self.connect(host, port)
def set_debuglevel(self, debuglevel):
"""Set the debug output level.
A non-false value results in debug messages for connection and
for all messages sent to and received from the server.
"""
self.debuglevel = debuglevel
def connect(self, host, port = 0):
"""Connect to a host on a given port.
Note: This method is automatically invoked by __init__,
if a host is specified during instantiation.
"""
if not port:
i = string.find(host, ':')
if i >= 0:
host, port = host[:i], host[i+1:]
try: port = string.atoi(port)
except string.atoi_error:
raise socket.error, "nonnumeric port"
if not port:
port = HTTP_PORT
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setblocking(0)
if self.debuglevel > 0:
print 'connect:', (host, port)
# This is kinda ugly, but a non-blocking connect() returns
# errno 36 ('Operation now in progress') and we don't want to
# catch that as an error. So we let select() find a trashed
# socket if it wants.
try:
result = self.sock.connect( (host, port) )
except socket.error, val:
if val[0] == errno.EINPROGRESS:
# 'Operation in Progress' is OK
pass
else:
self.valid = None
return
# wait for the connect to succeed, or time out in 10s
try:
(sread, swrite, serror) = select.select( [], [self.sock], [], 10 )
except select.error:
# there was a problem ...
# print "Select error %s: %s" (select.error)
self.valid = None
return
if swrite.count(self.sock) > 0 :
# Check the socket for an error
# we got the connection...
i = self.sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
if 0 == i:
self.valid = 1
self.sock.setblocking(1)
return
# otherwise, we hit the timeout
self.valid = None
def send(self, str):
"""Send `str' to the server."""
if self.debuglevel > 0: print 'send:', `str`
self.sock.send(str)
def putrequest(self, request, selector):
"""Send a request to the server.
`request' specifies an HTTP request method, e.g. 'GET'.
`selector' specifies the object being requested, e.g.
'/index.html'.
"""
if not selector: selector = '/'
self.metaHeader = '%s %s %s\r\n' % (request, selector, HTTP_VERSION)
def putheader(self, header, *args):
"""Send a request header line to the server.
For example: h.putheader('Accept', 'text/html')
"""
self.metaHeader = self.metaHeader + '%s: %s\r\n' % (header, string.joinfields(args,'\r\n\t'))
def endheaders(self):
"""Indicate that the last header line has been sent to the server."""
self.send('%s\r\n' % self.metaHeader)
def getreply(self, timeout):
"""Get a reply from the server.
Returns a tuple consisting of:
- server response code (e.g. '200' if all goes well)
- server response string corresponding to response code
- any RFC822 headers in the response from the server
"""
x = select.select([self.sock], [], [], timeout)
if ([], [], []) == x:
return -2, -2, -2
self.file = self.sock.makefile('rb')
line = self.file.readline()
if self.debuglevel > 0: print 'reply:', `line`
try:
[ver, code, msg] = string.split(line, None, 2)
except ValueError:
try:
[ver, code] = string.split(line, None, 1)
msg = ""
except ValueError:
self.headers = None
return -1, line, self.headers
if ver[:5] != 'HTTP/':
self.headers = None
return -1, line, self.headers
errcode = string.atoi(code)
errmsg = string.strip(msg)
self.headers = mimetools.Message(self.file, 0)
return errcode, errmsg, self.headers
def getfile(self):
"""Get a file object from which to receive data from the HTTP server.
NOTE: This method must not be invoked until getreplies
has been invoked.
"""
return self.file
def close(self):
"""Close the connection to the HTTP server."""
if self.file:
self.file.close()
self.file = None
if self.sock:
self.sock.close()
self.sock = None
def test():
"""Test this module.
The test consists of retrieving and displaying the Python
home page, along with the error code and error string returned
by the www.python.org server.
"""
import sys
import getopt
global DelaySecs
global DumpData
opts, args = getopt.getopt(sys.argv[1:], 'di:')
for o, a in opts:
if o == '-d': DumpData = 1
if o == '-i':
DelaySecs = float(a)
#print "DelaySecs: %s" %(DelaySecs)
host = 'www.redwoodsoft.com'
selector = '/'
if args[0:]: host = args[0]
if args[1:]: selector = args[1]
connectTime = -1
replyTime = -1
readTime = -1
startTime = time.time()
h = HTTP( host, 80 )
endTime = time.time()
connectTime = endTime - startTime
if h.valid == None:
print " [%s%s] Connect Timeout (%s secs) " % (host, selector, connectTime)
return
h.putrequest('GET', selector)
h.putheader('Host', host)
h.endheaders()
startTime = time.time()
errcode, errmsg, headers = h.getreply(5)
endTime = time.time()
replyTime = endTime - startTime
if errcode == -2:
print " [%s%s] Reply Timeout (%02.2f secs) " % (host, selector, replyTime)
return
f = h.getfile()
startTime = time.time()
webpage = f.read()
endTime = time.time()
readTime = endTime - startTime
year, month, day, hour, min, sec, dayofweek, dayofyear, x = time.localtime(time.time())
print "[%d/%d %02d:%02d:%02d] [%s%s] Reply [%s] Connect:[%0.4f] Reply:[%0.4f] Read:[%0.4f] " % (month, day, hour, min, sec, host, selector, errcode, connectTime, replyTime, readTime)
if DumpData:
print webpage
if __name__ == '__main__':
while 1:
test()
time.sleep(DelaySecs)