Is this a canonical Python HTTP POST with Basic Authentication?

Since I have the attention of some Pythonistas, I have another question about Python. Here's a basic command line script for posting an update to Twitter, not using any libraries:

import urllib
import urllib2
import httplib
import sys

if len(sys.argv) != 2:
    print "Please enter message"
    raise SystemExit

msg = sys.argv[1]

username = "user"
password = "pass"

url = "http://twitter.com/statuses/update.xml"

password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, "http://twitter.com/", username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
data = urllib.urlencode({'status' : msg})
req = urllib2.Request(url, data)
f = opener.open(req)

if f:
    print "Update OK!"
else:
    print "Error updating..."

I got the bulk of the code from this script, and just stripped it down to the very basics. If I had to write it all myself by using nothing but the documentation, I wouldn't have figured it out. The honest truth though is that I still don't understand most of it. The question is, is that really the most basic way to POST to a site that uses Basic Auth or is there something simpler?

Compare the above to what I'd do if I were using PHP:

#!/usr/bin/php -q
<?php

    $status = stripslashes($argv[1]);

    $username = 'user';
    $password = 'pass';

    $url = "http://$username:$password@twitter.com/statuses/update.xml";

    $params = array('http' => array(
                  'method' => 'POST',
                  'content' => 'status='. $status
               ));
     $ctx = stream_context_create($params);
     $fp = @fopen($url, 'rb', false, $ctx);
     $response = @stream_get_contents($fp);

     if ($response === false) {
          echo 'Failed to post';
     } else {
          echo 'Success!';
     }

And if I needed more power/reliability, I'd probably use PHP's integrated Curl support. I guess that's technically a third-party library, but not really as the docs are on the main PHP site and it's considered sort of standard for most PHP projects. Example:

#!/usr/bin/php -q
<?php

    $status = stripslashes($argv[1]);

    $postfields = 'status='. $status . '';

    $username = 'user';
    $password = 'pass';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://twitter.com/statuses/update.xml');
    curl_setopt($ch, CURLOPT_USERPWD,$username . ":" . $password);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);

    $data = curl_exec($ch);

    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if($http_code == 200){
        echo 'Success!';
    } else {
        echo 'Failed to post';
    }

So the question is, what's the standard Pythonic way of doing this stuff? Does it really need to be so complicated as my first code sample above? Looking through the web, in the documentation and in books, it's not clear to me if there's a more straight-forward way of doing it that I can understand easily and re-use quickly in scripts.

Thanks,

-Russ

Update: It looks like httplib2 is commonly used and recommended. Jacob gave me a sample POST using it in the comments and it's clean and works well. I modified the above code using it to this:


import urllib
import httplib2
import sys

if len(sys.argv) != 2:
    print "Please enter message"
    raise SystemExit

msg = sys.argv[1]

username = "user"
password = "pass"

http = httplib2.Http()
http.add_credentials(username, password)
response = http.request(
    "http://twitter.com/statuses/update.xml", 
    "POST", 
    urllib.urlencode({"status": msg})
)

if response:
    print "Update OK!"
else:
    print "Error updating..."

Cool beans.

-R

< Previous         Next >