htget.py
'''Get HTTP Resource.
Developer@Sonnack.com
April 2012
'''
from sys import stdin, stdout, stderr
from os import execl, path
from httplib import HTTPConnection, HTTPException
class htget (object):
'''HTTP Get class.'''
url = None
status = ''
headers = {}
txt = ''
def __init__ (self, _host, _path):
self.host = _host
self.path = _path
conn = HTTPConnection(self.host)
try:
conn.request('GET', self.path)
rqst = conn.getresponse()
self.statusCode = rqst.status
self.statusText = rqst.reason
self.status = str(self.statusCode) + ' ' + self.statusText
self.headers = rqst.msg
self.text = rqst.read()
except HTTPException as e:
self.status = 'ERR'
self.headers = {}
self.text = str(e)
def save (self, filename):
f = open(filename, 'wb')
try:
f.write(self.text)
except:
raise
finally:
f.close()
def __cmp__ (self, other):
return cmp(self.text, other.text)
def __len__ (self):
return len(self.text)
def __str__ (self):
return 'http://' + self.host + self.path
def __repr__ (self):
'''JSON-like string.'''
t = (self.host, self.path, self.status, len(self))
return '{htget: {host:"%s", path:"%s", status:"%s", size:%d}}' % t
def get_page (hostname, pagename, filename=None):
'''Get an http resource into a file and (optionally) view it.'''
print 'get-page/hostname: %s' % hostname
print 'get-page/pagename: %s' % pagename
print 'get-page/filename: %s' % filename
htobj = htget(hostname, pagename)
print htobj.status
print str(htobj)
print repr(htobj)
if filename:
htobj.save(filename)
print
print '[E](dit) + [Enter] (to open in gvim):'
print '[V](iew) + [Enter] (to open in iview):'
print
print '[Enter] (exit):'
print
cmd = stdin.readline()
cmd = cmd.strip().upper()
if cmd.startswith('E'):
execl(r'C:\CJS\bin\vim\vim73\gvim.exe', 'gview', filename)
if cmd.startswith('V'):
execl(r'C:\Program Files (x86)\IrfanView\i_view32.exe', 'iview', filename)
return htobj
'''eof'''