Skip to content

Instantly share code, notes, and snippets.

@hktechn0
Created November 28, 2011 05:37
Show Gist options
  • Save hktechn0/1399242 to your computer and use it in GitHub Desktop.
Save hktechn0/1399242 to your computer and use it in GitHub Desktop.
Twitpic v2 API wrapper for Python
#-*- coding: utf-8 -*-
# Twitpic API v2 wrapper methods
import httplib
import json
import email.mime.image
import email.mime.multipart
import email.mime.text
import email.encoders
import oauth
class Twitpic(object):
host = "api.twitpic.com"
url = "/2/upload.json"
verify_credentials_url = "https://api.twitter.com/1/account/verify_credentials.json"
def __init__(self, oauth, apikey):
self.oauth = oauth
self.apikey = apikey
def upload(self, filename, message = ""):
# img
image = open(filename)
imgdata = image.read()
image.close()
mimeimg = email.mime.image.MIMEImage(imgdata, _encoder = email.encoders.encode_noop)
mimeimg.add_header("Content-Disposition", "form-data", name = "media", filename = "image")
mimeimg.add_header("Content-Length", str(len(imgdata)))
# key
mimekey = email.mime.text.MIMEText(self.apikey)
mimekey.add_header("Content-Disposition", "form-data", name = "key")
# message
mimemsg = email.mime.text.MIMEText(message)
mimemsg.set_charset("utf-8")
mimemsg.add_header("Content-Disposition", "form-data", name = "message")
data = email.mime.multipart.MIMEMultipart("form-data")
data.attach(mimekey)
data.attach(mimemsg)
data.attach(mimeimg)
multipart = data.as_string()
boundary = data.get_boundary()
ctype, multipart = multipart.split("\n\n", 1)
c = httplib.HTTPConnection(self.host)
c.putrequest("POST", self.url)
c.putheader("Content-Length", str(len(multipart)))
c.putheader("Content-Type",
'multipart/form-data; boundary="%s"' % boundary)
oauth_header = self.oauth.oauth_header(
self.verify_credentials_url,
secret = self.oauth.asecret,
realm = "http://api.twitter.com/")
c.putheader("X-Auth-Service-Provider", self.verify_credentials_url)
c.putheader("X-Verify-Credentials-Authorization", oauth_header)
c.endheaders()
c.send(multipart)
response = c.getresponse().read()
return json.loads(response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment