]>
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
="", agent
="twitter.py"):
27 self
.username
= username
28 self
.password
= password
32 def __getattr__(self
, k
):
34 return object.__getattr
__(self
, k
)
35 except AttributeError:
37 self
.username
, self
.password
, self
.format
,
38 self
.uri
+ "/" + k
, self
.agent
40 def __call__(self
, **kwargs
):
42 if (self
.uri
.endswith('new')
43 or self
.uri
.endswith('update')
44 or self
.uri
.endswith('create')
45 or self
.uri
.endswith('destroy')):
48 if (self
.agent
and self
.uri
.endswith('update')):
49 kwargs
["source"] = self
.agent
51 encoded_kwargs
= urlencode(kwargs
.items())
53 if kwargs
and (method
== "GET"):
54 argStr
= "?" + encoded_kwargs
58 headers
["X-Twitter-Client"] = self
.agent
60 headers
["Authorization"] = "Basic " + b64encode("%s:%s" %(
61 self
.username
, self
.password
))
63 headers
["Content-type"] = "application/x-www-form-urlencoded"
64 headers
["Content-length"] = len(encoded_kwargs
)
66 c
= httplib
.HTTPConnection("twitter.com")
68 c
.putrequest(method
, "%s.%s%s" %(
69 self
.uri
, self
.format
, argStr
))
70 for item
in headers
.iteritems():
74 c
.send(encoded_kwargs
)
79 elif (r
.status
!= 200):
80 raise TwitterError("Twitter sent status %i: %s" %(
82 if "json" == self
.format
:
83 return json
.loads(r
.read())
89 class Twitter(TwitterCall
):
91 The minimalist yet fully featured Twitter API class.
93 Get RESTful data by accessing members of this class. The result
94 is decoded python objects (lists and dicts).
96 The Twitter API is documented here:
97 http://groups.google.com/group/twitter-development-talk/web/api-documentation
101 twitter = Twitter("hello@foo.com", "password123")
103 # Get the public timeline
104 twitter.statuses.public_timeline()
106 # Get a particular friend's timeline
107 twitter.statuses.friends_timeline(id="billybob")
109 # Also supported (but totally weird)
110 twitter.statuses.friends_timeline.billybob()
112 # Send a direct message
113 twitter.direct_messages.new(
115 text="I think yer swell!")
117 Using the data returned::
119 Twitter API calls return decoded JSON. This is converted into
120 a bunch of Python lists, dicts, ints, and strings. For example,
122 x = twitter.statuses.public_timeline()
124 # The first 'tweet' in the timeline
127 # The screen name of the user who wrote the first 'tweet'
128 x[0]['user']['screen_name']
130 Getting raw XML data::
132 If you prefer to get your Twitter data in XML format, pass
133 format="xml" to the Twitter object when you instantiate it:
135 twitter = Twitter(format="xml")
137 The output will not be parsed in any way. It will be a raw string
140 def __init__(self
, email
=None, password
=None, format
="json"):
142 Create a new twitter API connector using the specified
143 credentials (email and password). Format specifies the output
144 format ("json" (default) or "xml").
146 if (format
not in ("json", "xml")):
147 raise TwitterError("Unknown data format '%s'" %(format))
148 TwitterCall
.__init
__(self
, email
, password
, format
)
150 __all__
= ["Twitter", "TwitterError"]