example of using urllib2 with https urls

Larry Bates larry.bates at websafe.com
Tue Oct 18 15:53:43 EDT 2005


<snipped from working code to upload a file to https:
site---WARNING not tested after snipping>

import httplib
import base64
import sys
import random

#
# Get the length of the file from os.stat
#
username='<username>'
password='<password>'
file='<path to file to be uploaded>'
size=os.stat(file)[6]
#
# file contains the entire path, split off the name
# WebSafe.
#
name=os.path.basename(file)

url='https://www.somedomain.com'
auth_string = base64.encodestring('%s:%s' % (username, password))
rid = '%02x' % random.uniform(0, sys.maxint-1)

conn = httplib.HTTP(url)
conn.putrequest('PUT', '%s/%s' % (path, rid))
conn.putheader('Content-Type', 'text/plain')
conn.putheader('Content-Length', str(size))
conn.putheader('Authorization', 'Basic %s' % auth_string)
conn.endheaders()

#
# Open file in binary mode for reading
#
fp=open(file, 'rb')
#
# Loop over all the file's blocks and send them sequentially
#
blocknum=0
while 1:
    bodypart=fp.read(blocksize)
    blocknum+=1
    if blocknum % 10 == 0:
        print "upload-sending blocknum=", blocknum

    if not bodypart: break
    conn.send(bodypart)

fp.close()
reply, msg, headers = conn.getreply()
print "upload-PUT reply=", reply, " msg=", msg, "headers=", headers


<end snip>

This is for Basic Authentication (if your https site is using
something different, method would be different).  May not be what
you need.  Hope this helps.

Larry Bates

Michele Simionato wrote:
> Can somebody provide an example of how to retrieve a https url, given
> username and password? I don't find it in the standard documentation.
> TIA,
> 
>           Michele Simionato
> 



More information about the Python-list mailing list