Search code examples
pythonpython-2.7google-app-engineurllib2

How to make a urllib2 POST request without using urlopen?


Using python 2. I have a BasicAuthHandler which has been been installed as an opener which I'm using to make requests to one site.

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, base_url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)

I now want to make request to another site without the opener. I can't use the requests library since I'm using gooogle app engine and I'll have to install another library for it to work properly with GAE. So is there a way to uninstall an opener before making this request and reinstall it again?


Solution

  • You can build and install a different opener. This is how I do it:

    opener2 = urllib2.OpenerDirector()
    default_classes = [urllib2.HTTPHandler, urllib2.HTTPDefaultErrorHandler,
                       MyFTPHandler, urllib2.HTTPErrorProcessor]
    if hasattr(httplib, 'HTTPS'):
        default_classes.insert(0, urllib2.HTTPSHandler)
    for klass in default_classes:
        opener2.add_handler(klass())
    
    urllib2.install_opener(opener2)
    

    Use and then return to the first opener (urllib2.install_opener(opener)).