]>
jfr.im git - z_archive/twitter.git/blob - twitter/api.py
4 from exceptions
import Exception
6 from twitter
.twitter_globals
import POST_ACTIONS
7 from twitter
.auth
import UserPassAuth
, NoAuth
11 return sys
.hexversion
> 0x20600f0
16 import simplejson
as json
18 class TwitterError(Exception):
20 Base Exception thrown by the Twitter object when there is a
21 general error interacting with the API.
25 class TwitterHTTPError(TwitterError
):
27 Exception thrown by the Twitter object when there is an
28 HTTP error interacting with twitter.com.
30 def __init__(self
, e
, uri
, format
, encoded_args
):
34 self
.encoded_args
= encoded_args
38 "Twitter sent status %i for URL: %s.%s using parameters: "
39 "(%s)\ndetails: %s" %(
40 self
.e
.code
, self
.uri
, self
.format
, self
.encoded_args
,
43 class TwitterCall(object):
45 self
, auth
, format
, domain
, uri
="", agent
=None,
46 encoded_args
=None, secure
=True):
52 self
.encoded_args
= encoded_args
55 def __getattr__(self
, k
):
57 return object.__getattr
__(self
, k
)
58 except AttributeError:
60 self
.auth
, self
.format
, self
.domain
,
61 self
.uri
+ "/" + k
, self
.agent
, self
.encoded_args
, self
.secure
)
63 def __call__(self
, **kwargs
):
64 uri
= self
.uri
.strip("/")
66 for action
in POST_ACTIONS
:
67 if self
.uri
.endswith(action
):
70 kwargs
["source"] = self
.agent
79 uriBase
= "http%s://%s/%s%s%s" %(
80 secure_str
, self
.domain
, uri
, dot
, self
.format
)
82 if (not self
.encoded_args
):
83 if kwargs
.has_key('id'):
84 uri
+= "/%s" %(kwargs
['id'])
86 self
.encoded_args
= self
.auth
.encode_params(uriBase
, method
, kwargs
)
92 argStr
= "?%s" %(self
.encoded_args
)
94 argData
= self
.encoded_args
98 headers
["X-Twitter-Client"] = self
.agent
99 if self
.auth
is not None:
100 headers
.update(self
.auth
.generate_headers())
102 req
= urllib2
.Request(uriBase
+argStr
, argData
, headers
)
105 handle
= urllib2
.urlopen(req
)
106 if "json" == self
.format
:
107 return json
.loads(handle
.read())
110 except urllib2
.HTTPError
, e
:
114 raise TwitterHTTPError(e
, uri
, self
.format
, self
.encoded_args
)
116 class Twitter(TwitterCall
):
118 The minimalist yet fully featured Twitter API class.
120 Get RESTful data by accessing members of this class. The result
121 is decoded python objects (lists and dicts).
123 The Twitter API is documented here:
125 http://apiwiki.twitter.com/
126 http://groups.google.com/group/twitter-development-talk/web/api-documentation
131 auth=OAuth(token, token_key, con_secret, con_secret_key)))
133 # Get the public timeline
134 twitter.statuses.public_timeline()
136 # Get a particular friend's timeline
137 twitter.statuses.friends_timeline(id="billybob")
139 # Also supported (but totally weird)
140 twitter.statuses.friends_timeline.billybob()
142 # Send a direct message
143 twitter.direct_messages.new(
145 text="I think yer swell!")
150 twitter_search = Twitter(domain="search.twitter.com")
152 # Find the latest search trends
153 twitter_search.trends()
155 # Search for the latest News on #gaza
156 twitter_search.search(q="#gaza")
159 Using the data returned
160 -----------------------
162 Twitter API calls return decoded JSON. This is converted into
163 a bunch of Python lists, dicts, ints, and strings. For example::
165 x = twitter.statuses.public_timeline()
167 # The first 'tweet' in the timeline
170 # The screen name of the user who wrote the first 'tweet'
171 x[0]['user']['screen_name']
177 If you prefer to get your Twitter data in XML format, pass
178 format="xml" to the Twitter object when you instantiate it::
180 twitter = Twitter(format="xml")
182 The output will not be parsed in any way. It will be a raw string
187 self
, email
=None, password
=None, format
="json",
188 domain
="twitter.com", agent
=None, secure
=True, auth
=None,
191 Create a new twitter API connector.
193 Pass an `auth` parameter to use the credentials of a specific
194 user. Generally you'll want to pass an `OAuth`
197 twitter = Twitter(auth=OAuth(
198 token, token_secret, consumer_key, consumer_secret))
201 Alternately you can pass `email` and `password` parameters but
202 this authentication mode will be deactive by Twitter very soon
203 and is not recommended::
205 twitter = Twitter(email="blah@blah.com", password="foobar")
208 `domain` lets you change the domain you are connecting. By
209 default it's twitter.com but `search.twitter.com` may be
212 If `secure` is False you will connect with HTTP instead of
215 The value of `agent` is sent in the `X-Twitter-Client`
216 header. This is deprecated. Instead Twitter determines the
217 application using the OAuth Client Key and Client Key Secret
220 `api_version` is used to set the base uri. By default it's
221 nothing, but if you set it to '1' your URI will start with
225 if email
is not None or password
is not None:
228 "Can't specify 'email'/'password' and 'auth' params"
230 auth
= UserPassAuth(email
, password
)
235 if (format
not in ("json", "xml", "")):
236 raise ValueError("Unknown data format '%s'" %(format))
240 uri
= str(api_version
)
242 TwitterCall
.__init
__(
243 self
, auth
, format
, domain
, uri
, agent
,
246 __all__
= ["Twitter", "TwitterError", "TwitterHTTPError"]