# Name:		httpPyDemo.py
# Author:	Dave Renner		dmrenne@comcast.net
# Date:		09/01/11      1400
# Rev:		09/24/12		1915
# Note:		this is a called module of 'pyDemo.py'
#
# Note:		'httpPyDemo.py' demos how to set up and use HTTP to a URL,
#			as well as the time/date function
#
#
# ###################################################################
import time

hostgator_HEAD_working = 0      # doesnt seem to work
putheader_working = 1           # works now! (surprise!)
testing_http = 0                # works on 2.6, not on 3.0
testing_urllib = 1              # always works
my_url  = "http://www.maklisco.com/myPyTest.html"
#my_url = "http://www.maklisco.com"

# ############################ BOILERPLATE ##########################
import pickle

myConfigFile = 'pyDemoConfig.dat'

# version has been stored in our calling module 'pyDemo.py'
PythonVersFile = 'version.obj'
versfile = open(PythonVersFile, 'rb')
PythonVers = pickle.load(versfile)
versfile.close()

if PythonVers == '30':
    import urllib.request
    import http.client	
    import configparser
    config = configparser.ConfigParser()
    input_cmd = 'input'
else:
    import urllib
    import httplib
    import ConfigParser
    config = ConfigParser.ConfigParser()
    input_cmd = 'raw_input'

config.read(myConfigFile)
interactive = config.get('Mode', 'interactive')
continue_cmd = config.get('Strings', 'continue_cmd')

# easier to just include this boilerplate function into every module 
# than to import it
def printf(arg):
    cmdText = "print "
    arg_nonSlash = arg.strip('\\')
    if PythonVers == '30':
        cmdFull = cmdText + '("' + arg_nonSlash + '")'
    else:
        cmdFull = cmdText + '"' + arg_nonSlash + '"'
    exec( cmdFull )
	
# ###################################################################

printf("We are now in module 'httpPyDemo'. We will now begin\
\\nMarching Up and Down the Square.\
\\n\
\\nJust kidding. Silly me!\
\\n\
\\nWe will now test the use of two Python modules\
\\nthat connect to the Internet, 'httplib' and 'urllib'.\
\\nWe must say at the outset that there are different versions,\
\\nwith different names, for these modules, depending on\
\\nyou're using Python 3.0 or 2.6.\
\\nAnd some of the functions in 2.6 are no longer supported\
\\nin 3.0, though 3.0 still supports the same functionality,\
\\njust using different functions.")
printf("")
if interactive == '1':
	printf("")
	full_cmd = input_cmd + '("' + continue_cmd + '")'
	eval(full_cmd)	

	printf("")
printf('BTW, the date/time is:')
mytime = time.strftime('%I:%M %p, %B %d, %Y')
printf(mytime)
printf("")
printf("")

# ######################################################################

#conn = httplib.HTTPConnection('www.maklisco.com')
if PythonVers == '30':
    conn = http.client.HTTPConnection('www.maklisco.com')
else:
    conn = httplib.HTTP('www.maklisco.com')

# it always does	
if putheader_working:
    printf("First we will put a header request to our website.\
\\nThis is a boilerplate message to our web host\
\\nto tell it that that we are accepting responses\
\\nin 'text/html' format.\
\\n\
\\nThis is significant because here we are using a Python\
\\nscript to 'program' HTTP, the protocol of the Web.\
\\n\
\\nUsually we do this with higher-level admin tools, but here\
\\nwe do it in Python program that needs no human intervention,\
\\nwhich can be very useful if we're using Python\
\\nto send/receive files to/from a website,\
\\n without using the insecure protocol ftp.\
\\n\
\\nP.S.: I've used this kind of programming in real life...")
    # 'HTTP' uses 'putrequest', 'HTTPConnection' uses 'request'
    conn.putrequest("POST", "/public_html/index.html")
    #conn.putheader("Accept", "text/html")
    conn.putheader("Accept", "jpeg")
    #conn.putheader("Cache-Control:", "no-cache")
    #conn.putheader("User-Agent:", "dmrenne@maklisco.com")
    #conn.putheader("From", "dmrenne@maklisco.com")
    conn.endheaders()
    printf("")
    printf('We have now posted a header!')

printf("")
if interactive == '1':
	printf("")
	full_cmd = input_cmd + '("' + continue_cmd + '")'
	eval(full_cmd)	

	
# I don't think my webhost processes the HEAD command.
# It's really not necessary, after all
if hostgator_HEAD_working:
    conn.request("HEAD", "/public_html/index.html")
    resp = conn.getresponse()
    data = resp.read()
    printf("to print response: ")
    printf( data )

	
# this doesn't work under 3.0, so forget about it.
# We don't need it anyway
if testing_http:
    conn.connect()
    printf('made the connection to maklisco!')
    conn.request("GET", "/public_html/index.html")
    resp = conn.getresponse()
    data = resp.read()
    printf( data )
    conn.close()


# we always will
if testing_urllib:
    printf("We are now using 'urllib' to open the 'my.html' file\
\\non my website. This is an alternative to 'httplib',\
\\nwhich no longer seems to be supported on 3.0.\
\\nNote that if we failed to provide a filename parameter here,\
\\nurllib will open the default 'index.html', put up\
\\nby the website provider!\
\\n\
\\nIt will NOT open the 'index.html' that I have supplied,\
\\nthe one that users get to when they go to my website\
\\nvia a browser!\
\\n\
\\nThis seems strange to me...")
    printf("Oh, well...")

    printf("")
    if PythonVers == '30':
        my_file = urllib.request.urlopen(my_url)
    else:
        my_file = urllib.urlopen(my_url)

    my_data = my_file.read()
    if PythonVers == '30':
        printf( str(my_data) )
    else:
        # my 'printf()' doesnt work well with HTML, containing embed strings
        # One of these days I'll make 'printf' more versatile.
        # Basically, I consider it a kludge to present this demo for both
        # 3.0 and 2.6
        pdata = str(my_data)
        print (pdata)
    printf("")
    printf("Jolly good. We displayed my 'basic' HTML file")

printf("We will stop this test now because it is entirely\
\\ntoo silly! Very silly, indeed.")
