Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Wednesday, May 7, 2008

My First Digg API Application

Here is my very first Python program that I've ever wrote outside of a classroom. Basically, it display informations of all Digg friends.

One thing I need to figure out is how to handle non-ASCII characters. My code throws exception when it encounter Unicode or non-printable characters in full name.

import urllib
import xml.etree.ElementTree as ET

# You need to changes following lines 
uname = 'myusername'
appkey = urllib.quote('http://my.web.site/')

# ---------------------------------------------------------

count = 100
offset = 0
class AppURLopener(urllib.FancyURLopener):
  version = "My-Application/1.0"
urllib._urlopener = AppURLopener()
optstr = "&count=" + str(count) + "&offset=" + str(offset)
diggurl = 'http://services.digg.com/user/' + uname + \
            '/friends' + '?appkey=' + appkey + optstr;
diggxml = urllib.urlopen(diggurl).read()
et = ET.fromstring(diggxml)
nfriend = int(et.attrib["total"])

while True:

  for e in et:
    name = e.get("name", "")
    icon = e.get("icon", "")
    registered = e.get("registered", "")
    profileviews = e.get("profileviews", "")
    # Some of names contains non-ASCII character which
    # I still having figure out how to handle it
    # fullname = e.get("fullname", "")
    fullname = ""
    mutual = e.get("mutual", "")
    date = e.get("date", "")  
    print name + "|" + icon + "|" + registered + "|" + \
            profileviews + "|" + fullname + "|" +      \
            mutual + "|" + date
 
  offset += count
  if offset >= nfriend:
    break
  optstr = "&count=" + str(count) + "&offset=" + \
            str(offset)
  diggurl = 'http://services.digg.com/user/' + uname +   \
            '/friends' + '?appkey=' + appkey + optstr;
  diggxml = urllib.urlopen(diggurl).read()
  et = ET.fromstring(diggxml)