Being slightly ADD I tend to be the kind that starts lots of projects. Reversing projects, webapp projects, coding little utilities I've wanted, even rewritting pieces of code that other people have already written just for my own education. Sadly that also means that when I get hung up on something it's easy to push it aside, not finish it, and work on something else. It's been a personal goal recently to complete a bunch of these 3/4 of the way complete projects before I start the multitude of new one I have in mind.
One of these has been a Python Twitter client/libary. Something to hook when I want to access Twitter for some of my other projects and to use for CLI Twitter access, being a Terminal nerd like that. Basic enough, it was before I'd been writing a lot of code, I wanted to work with a web API of some kind, and it helps that I know the guy who maintains the Twitter API in case I ever have questions. My implimentation has been pretty straight forward, the API is easy to use, documentation very through, and I got everything together with just one little (little being used sarcasticly) issue: authentication.
BasicAuth is straight forward enough. Seemed simple. Yet after reading more than a dozen documents, reviwing code in a number of other applications, and reading the urllib2 spec a number of times I could never successfully authenticate. Finally I stumbled across someone else who had the same issue, and found the answer in httplib. After playing around with his code the following works:
#!/usr/bin/env python
import sys, os
import httplib, urllib, base64
class BasicAuth():
def __init__(self, username, password, url):
"""Builds class. Creates authentication and connection objects."""
self.authentication = { "Authorization": "Basic %s" % base64.encodestring("%s:%s" % (username, password)).strip() }
self.connection = httplib.HTTPConnection(url, 80)
def get(self, path):
"""Generates and executes authenticated GET request."""
try:
self.connection.request("GET", path, urllib.urlencode({}), self.authentication)
response = self.connection.getresponse()
except:
print >> sys.stderr, "Get Request: Failed"
else:
return response.read()
def post(self, path, type, content):
"""Generates and executes authenticated POST request."""
try:
self.connection.request("POST", path, urllib.urlencode({ type: content }), self.authentication)
response = self.connection.getresponse()
except:
print >> sys.stderr, "Post Request: Failed"
else:
return response.status, reponse.reason
import httplib, urllib, base64
class BasicAuth():
def __init__(self, username, password, url):
"""Builds class. Creates authentication and connection objects."""
self.authentication = { "Authorization": "Basic %s" % base64.encodestring("%s:%s" % (username, password)).strip() }
self.connection = httplib.HTTPConnection(url, 80)
def get(self, path):
"""Generates and executes authenticated GET request."""
try:
self.connection.request("GET", path, urllib.urlencode({}), self.authentication)
response = self.connection.getresponse()
except:
print >> sys.stderr, "Get Request: Failed"
else:
return response.read()
def post(self, path, type, content):
"""Generates and executes authenticated POST request."""
try:
self.connection.request("POST", path, urllib.urlencode({ type: content }), self.authentication)
response = self.connection.getresponse()
except:
print >> sys.stderr, "Post Request: Failed"
else:
return response.status, reponse.reason
I don't know exactly why the httplib method works so easily and the urllib2 method constantly failed inspite of my constant efforts. Thankfully the rest of the code I'd written worked flawlessly. It's got a few more hours of cleanup, but I'm hoping to have it ready for release this week. Until then, here's working, easy, BasicAuth for your Python based enjoyment.
