]>
jfr.im git - z_archive/twitter.git/blob - twitter/api.py
2 from base64
import b64encode
3 from urllib
import urlencode
7 from exceptions
import Exception
9 class TwitterError(Exception):
11 Exception thrown by the Twitter object when there is an
12 error interacting with twitter.com.
16 class TwitterCall(object):
17 def __init__(self
, username
, password
, format
, uri
=""):
18 self
.username
= username
19 self
.password
= password
22 def __getattr__(self
, k
):
24 return object.__getattr
__(self
, k
)
25 except AttributeError:
27 self
.username
, self
.password
, self
.format
,
29 def __call__(self
, **kwargs
):
31 if (self
.uri
.endswith('new')
32 or self
.uri
.endswith('update')
33 or self
.uri
.endswith('create')):
37 argStr
= "?" + urlencode(kwargs
.items())
38 c
= httplib
.HTTPConnection("twitter.com")
40 c
.putrequest(method
, "/%s.%s%s" %(
41 self
.uri
, self
.format
, argStr
))
44 "Authorization", "Basic " + b64encode("%s:%s" %(
45 self
.username
, self
.password
)))
46 if (method
== "POST"):
47 # TODO specify charset
53 elif (r
.status
!= 200):
54 raise TwitterError("Twitter sent status %i: %s" %(
56 if ("json" == self
.format
):
58 return simplejson
.loads(r
.read())
64 class Twitter(TwitterCall
):
66 The minimalist yet fully featured Twitter API class.
68 Get RESTful data by accessing members of this class. The result
69 is decoded python objects (lists and dicts).
71 The Twitter API is documented here:
72 http://groups.google.com/group/twitter-development-talk/web/api-documentation
76 twitter = Twitter("hello@foo.com", "password123")
78 # Get the public timeline
79 twitter.statuses.public_timeline()
81 # Get a particular friend's timeline
82 twitter.statuses.friends_timeline(id="billybob")
84 # Also supported (but totally weird)
85 twitter.statuses.friends_timeline.billybob()
87 # Send a direct message
88 twitter.direct_messages.new(
90 text="I think yer swell!")
92 Using the data returned::
94 Twitter API calls return decoded JSON. This is converted into
95 a bunch of Python lists, dicts, ints, and strings. For example,
97 x = twitter.statuses.public_timeline()
99 # The first 'tweet' in the timeline
102 # The screen name of the user who wrote the first 'tweet'
103 x[0]['user']['screen_name']
105 Getting raw XML data::
107 If you prefer to get your Twitter data in XML format, pass
108 format="xml" to the Twitter object when you instantiate it:
110 twitter = Twitter(format="xml")
112 The output will not be parsed in any way. It will be a raw string
115 def __init__(self
, email
=None, password
=None, format
="json"):
117 Create a new twitter API connector using the specified
118 credentials (email and password). Format specifies the output
119 format ("json" (default) or "xml").
121 if (format
not in ("json", "xml")):
122 raise TwitterError("Unknown data format '%s'" %(format))
123 if (format
== "json"):
128 "format not available: simplejson is not installed")
129 TwitterCall
.__init
__(self
, email
, password
, format
)
131 __all__
= ["Twitter"]