Advertisement
Guest User

crashsystems

a guest
Nov 1st, 2008
588
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.36 KB | None | 0 0
  1. """
  2. Author: Douglass Clem, crashsystems.net
  3. Title: PyTwitPic
  4. Description: As the name implies, PyTwitPic is a simple Python implementation
  5. of the Twitpic.com API.
  6. License: GPL v3
  7. """
  8.  
  9. import pycurl
  10. from BeautifulSoup import BeautifulStoneSoup #for xml parsing
  11.  
  12. # I'm setting up some variables for the API URLs, so that there will be one
  13. # easy place to change them in the future.
  14. upload_url = "http://twitpic.com/api/upload"
  15. upload_post_url = "http://twitpic.com/api/uploadAndPost"
  16.  
  17. def upload(username, password, file_path):
  18.     """Uploads the specified picture file. Returns URL of picture when upload
  19.    succeeds, and an error message when it fails."""
  20.    
  21.     #Post the pic
  22.     server = pycurl.Curl()
  23.     server.setopt(server.POST, 1)
  24.     server.setopt(server.URL, upload_url)
  25.     server.setopt(server.HTTPPOST, [("media", (server.FORM_FILE, file_path)),
  26.         ("username", username), ("password", password)])
  27.     xml = server.perform()
  28.    
  29.     #Now we have the raw XML response, so let's get the useful bits out of it.
  30.     response = __parse_xml(xml)
  31.    
  32.     return response
  33.  
  34. def upload_post(username, password, file_path, message):
  35.     """Uploads the specified picture and posts the status message. Returns URL
  36.    when it succeeds, and an error message when it fails."""
  37.    
  38.     #Post the pic
  39.     server = pycurl.Curl()
  40.     server.setopt(server.POST, 1)
  41.     server.setopt(server.URL, upload_url)
  42.     server.setopt(server.HTTPPOST, [("media", (server.FORM_FILE, file_path)),
  43.         ("username", username), ("password", password), ("message", message)])
  44.     xml = server.perform()
  45.    
  46.     #Now we have the raw XML response, so let's get the useful bits out of it.
  47.     status = __parse_xml(xml)
  48.    
  49.    
  50.     return status
  51.  
  52. def __parse_xml(raw_message):
  53.     """This function is not part of the API, but is used within the module to
  54.    process the xml response sent from twitpic.com."""
  55.    
  56.     soup = BeautifulStoneSoup(raw_message)
  57.  
  58.     if (len(soup.findAll(stat="ok")) == 1):
  59.         return str(soup.rsp.mediaurl.contents)
  60.     elif (len(soup.findAll(code="1001")) == 1):
  61.         return "Invalid twitter username or password"
  62.     elif (len(soup.findAll(code="1002")) == 1):
  63.         return "Image not found"
  64.     elif (len(soup.findAll(code="1003")) == 1):
  65.         return "Invalid image type"
  66.     else:
  67.         return "Image larger than 4MB"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement