]>
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
11 return sys
.hexversion
> 0x20600f0
16 import simplejson
as json
18 class TwitterError(Exception):
20 Exception thrown by the Twitter object when there is an
21 error interacting with twitter.com.
25 class TwitterCall(object):
26 def __init__(self
, username
, password
, format
, uri
=""):
27 self
.username
= username
28 self
.password
= password
31 def __getattr__(self
, k
):
33 return object.__getattr
__(self
, k
)
34 except AttributeError:
36 self
.username
, self
.password
, self
.format
,
38 def __call__(self
, **kwargs
):
40 if (self
.uri
.endswith('new')
41 or self
.uri
.endswith('update')
42 or self
.uri
.endswith('create')
43 or self
.uri
.endswith('destroy')):
46 encoded_kwargs
= urlencode(kwargs
.items())
48 if kwargs
and (method
== "GET"):
49 argStr
= "?" + encoded_kwargs
53 headers
["Authorization"] = "Basic " + b64encode("%s:%s" %(
54 self
.username
, self
.password
))
56 headers
["Content-type"] = "application/x-www-form-urlencoded"
57 headers
["Content-length"] = len(encoded_kwargs
)
59 c
= httplib
.HTTPConnection("twitter.com")
61 c
.putrequest(method
, "%s.%s%s" %(
62 self
.uri
, self
.format
, argStr
))
63 for item
in headers
.iteritems():
67 c
.send(encoded_kwargs
)
72 elif (r
.status
!= 200):
73 raise TwitterError("Twitter sent status %i: %s" %(
75 if "json" == self
.format
:
76 return json
.loads(r
.read())
82 class Twitter(TwitterCall
):
84 The minimalist yet fully featured Twitter API class.
86 Get RESTful data by accessing members of this class. The result
87 is decoded python objects (lists and dicts).
89 The Twitter API is documented here:
90 http://groups.google.com/group/twitter-development-talk/web/api-documentation
94 twitter = Twitter("hello@foo.com", "password123")
96 # Get the public timeline
97 twitter.statuses.public_timeline()
99 # Get a particular friend's timeline
100 twitter.statuses.friends_timeline(id="billybob")
102 # Also supported (but totally weird)
103 twitter.statuses.friends_timeline.billybob()
105 # Send a direct message
106 twitter.direct_messages.new(
108 text="I think yer swell!")
110 Using the data returned::
112 Twitter API calls return decoded JSON. This is converted into
113 a bunch of Python lists, dicts, ints, and strings. For example,
115 x = twitter.statuses.public_timeline()
117 # The first 'tweet' in the timeline
120 # The screen name of the user who wrote the first 'tweet'
121 x[0]['user']['screen_name']
123 Getting raw XML data::
125 If you prefer to get your Twitter data in XML format, pass
126 format="xml" to the Twitter object when you instantiate it:
128 twitter = Twitter(format="xml")
130 The output will not be parsed in any way. It will be a raw string
133 def __init__(self
, email
=None, password
=None, format
="json"):
135 Create a new twitter API connector using the specified
136 credentials (email and password). Format specifies the output
137 format ("json" (default) or "xml").
139 if (format
not in ("json", "xml")):
140 raise TwitterError("Unknown data format '%s'" %(format))
141 TwitterCall
.__init
__(self
, email
, password
, format
)
143 __all__
= ["Twitter", "TwitterError"]