urllib2 opendirector versus request object

D

Dennis

Hi,

I was wondering what the difference or advantages to using an
opendirector with handlers or using a request object?

I am having an issue where when I use the open director and I try to
add headers it adds them after the connection-close header, but when I
use the request object it does not.

Here is the headers as reported by python:
send: 'POST /xml-api/listaccts HTTP/1.1\r\nAccept-Encoding:
identity\r\nContent-Length: 13\r\nHost:
cpanel01.sea.fibercloud.com:2086\r\nContent-Type:
application/x-www-form-urlencoded\r\nConnection: close\r\nUser-Agent:
Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv,1.9.2.13)
Gecko/20101203 Firefox/3.6.13\r\n\r\n'
send: 'domain=anjopa'
reply: 'HTTP/1.1 403 Forbidden\r\n'
header: Connection: close
header: Server: cpsrvd/11.30.0.27
header: Content-type: text/xml

Next two examples one with Request object and the next with the open director,

#!/usr/bin/python
import sys
from xml.dom.minidom import parse, parseString
import urllib
import urllib2
import base64
from cookielib import CookieJar

# Turn on HTTP debugging
http://diveintopython.org/http_web_services/user_agent.html
import httplib



#With Request object:

req = urllib2.Request(url, {},{'Authorization':'Basic ' +
base64.b64encode( username + ':' + password ) } )
res = urllib2.urlopen(req)
print res.read()

With open director:
# Instantiate and Initialize AuthInfo Handler for use w/ the build_opener

authinfo = urllib2.HTTPBasicAuthHandler()
authinfo.add_password(realm="Web Host Manager",
uri="http://servername:2086/xml-api/listacct",
user="username",
passwd="password")

# Instantiate Cookie jar Handler for use w/ build_opener

cj = CookieJar()

# Create an opener object from list of handlers above
opener = urllib2.build_opener(authinfo,urllib2.HTTPCookieProcessor(cj),
urllib2.HTTPHandler(debuglevel=1))
urllib2.install_opener(opener)

opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U;
Windows NT 6.1; en-US; rv,1.9.2.13) Gecko/20101203 Firefox/3.6.13')]
response = opener.open(url, paramaters)





Dennis O.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top