htget.py

'''Get HTTP Resource.

Developer@Sonnack.com
April 2012
'''
####################################################################################################
from sys import stdinstdoutstderr
from os import execlpath
from httplib import HTTPConnectionHTTPException
####################################################################################################


##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
class htget (object):
    '''HTTP Get class.'''
    url = None
    status = ''
    headers = {}
    txt = ''

    def __init__ (self_host_path):
        self.host = _host
        self.path = _path

        # Get XML Document...
        conn = HTTPConnection(self.host)
        try:
            conn.request('GET'self.path)
            rqst = conn.getresponse()
            # Success (if we get this far)...
            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 (selffilename):
        f = open(filename'wb')
        try:
            f.write(self.text)
        except:
            raise
        finally:
            f.close()

    def __cmp__ (selfother):
        return cmp(self.textother.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.hostself.pathself.statuslen(self))
        return '{htget: {host:"%s", path:"%s", status:"%s", size:%d}}' % t


##================================================================================================##
def get_page (hostnamepagenamefilename=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

    # Fetch it...
    htobj = htget(hostnamepagename)
    # Print it...
    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()
        # Open with text editor...
        if cmd.startswith('E'):
            execl(r'C:\CJS\bin\vim\vim73\gvim.exe''gview'filename)
        # Open with image viewer...
        if cmd.startswith('V'):
            execl(r'C:\Program Files (x86)\IrfanView\i_view32.exe''iview'filename)

    return htobj


'''eof'''