Updating a Twitter profile image using Python and cURL

I’ve been trying for ages to update the Twitter profile image from Python and getting lost in multipart boundary rubbish. It seems as though its a fairly ad-hoc part of the Twitter API that hasn’t ever been updated. PyTwitter doesn’t handle it currently which is being used for all the other Twitter updates being done.

Finally here is a working method using PycURL. Thanks to pieceofpy for solving the actual syntax for form file uploads.

def SetProfileImage(self, filename):
import pycurl
url = 'https://twitter.com/account/update_profile_image.xml'
head = ['Expect: ']
data = [('image', (pycurl.FORM_FILE, filename))]
c = pycurl.Curl()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.USERPWD, "%s:%s" % (self.user, self.passwd))
c.setopt(pycurl.HTTPHEADER, head)
c.setopt(pycurl.HTTPPOST, data)
c.perform()
c.close()

This is the equivalent of the curl command

curl -u anxiousdoor:xxxxxxxx --header "Expect: " -F image="@/home/rossetti/door/icon-unlocked.png" https://twitter.com/account/update_profile_image.xml