]>
jfr.im git - z_archive/twitter.git/blob - twitter/api.py
3 from exceptions
import Exception
5 from twitter
.twitter_globals
import POST_ACTIONS
6 from twitter
.auth
import NoAuth
10 return sys
.hexversion
> 0x20600f0
15 import simplejson
as json
17 class TwitterError(Exception):
19 Base Exception thrown by the Twitter object when there is a
20 general error interacting with the API.
24 class TwitterHTTPError(TwitterError
):
26 Exception thrown by the Twitter object when there is an
27 HTTP error interacting with twitter.com.
29 def __init__(self
, e
, uri
, format
, uriparts
):
33 self
.uriparts
= uriparts
37 "Twitter sent status %i for URL: %s.%s using parameters: "
38 "(%s)\ndetails: %s" %(
39 self
.e
.code
, self
.uri
, self
.format
, self
.uriparts
,
42 class TwitterCall(object):
44 self
, auth
, format
, domain
, uri
="", agent
=None,
45 uriparts
=None, secure
=True):
51 self
.uriparts
= uriparts
54 def __getattr__(self
, k
):
56 return object.__getattr
__(self
, k
)
57 except AttributeError:
59 auth
=self
.auth
, format
=self
.format
, domain
=self
.domain
,
60 agent
=self
.agent
, uriparts
=self
.uriparts
+ (k
,),
63 def __call__(self
, **kwargs
):
66 for uripart
in self
.uriparts
:
67 # If this part matches a keyword argument, use the
68 # supplied value otherwise, just use the part.
69 uriparts
.append(kwargs
.pop(uripart
, uripart
))
70 uri
= '/'.join(uriparts
)
73 for action
in POST_ACTIONS
:
74 if uri
.endswith(action
):
78 # If an id kwarg is present and there is no id to fill in in
79 # the list of uriparts, assume the id goes at the end.
80 id = kwargs
.pop('id', None)
90 uriBase
= "http%s://%s/%s%s%s" %(
91 secure_str
, self
.domain
, uri
, dot
, self
.format
)
95 headers
.update(self
.auth
.generate_headers())
96 arg_data
= self
.auth
.encode_params(uriBase
, method
, kwargs
)
98 uriBase
+= '?' + arg_data
103 req
= urllib2
.Request(uriBase
, body
, headers
)
106 handle
= urllib2
.urlopen(req
)
107 if "json" == self
.format
:
108 return json
.loads(handle
.read())
111 except urllib2
.HTTPError
, e
:
115 raise TwitterHTTPError(e
, uri
, self
.format
, arg_data
)
117 class Twitter(TwitterCall
):
119 The minimalist yet fully featured Twitter API class.
121 Get RESTful data by accessing members of this class. The result
122 is decoded python objects (lists and dicts).
124 The Twitter API is documented here:
126 http://dev.twitter.com/doc
132 auth=OAuth(token, token_key, con_secret, con_secret_key)))
134 # Get the public timeline
135 twitter.statuses.public_timeline()
137 # Get a particular friend's timeline
138 twitter.statuses.friends_timeline(id="billybob")
140 # Also supported (but totally weird)
141 twitter.statuses.friends_timeline.billybob()
143 # Send a direct message
144 twitter.direct_messages.new(
146 text="I think yer swell!")
148 # Get the members of a particular list of a particular friend
149 twitter.user.listname.members(user="billybob", listname="billysbuds")
154 twitter_search = Twitter(domain="search.twitter.com")
156 # Find the latest search trends
157 twitter_search.trends()
159 # Search for the latest News on #gaza
160 twitter_search.search(q="#gaza")
163 Using the data returned
164 -----------------------
166 Twitter API calls return decoded JSON. This is converted into
167 a bunch of Python lists, dicts, ints, and strings. For example::
169 x = twitter.statuses.public_timeline()
171 # The first 'tweet' in the timeline
174 # The screen name of the user who wrote the first 'tweet'
175 x[0]['user']['screen_name']
181 If you prefer to get your Twitter data in XML format, pass
182 format="xml" to the Twitter object when you instantiate it::
184 twitter = Twitter(format="xml")
186 The output will not be parsed in any way. It will be a raw string
192 domain
="twitter.com", secure
=True, auth
=None,
195 Create a new twitter API connector.
197 Pass an `auth` parameter to use the credentials of a specific
198 user. Generally you'll want to pass an `OAuth`
201 twitter = Twitter(auth=OAuth(
202 token, token_secret, consumer_key, consumer_secret))
205 `domain` lets you change the domain you are connecting. By
206 default it's twitter.com but `search.twitter.com` may be
209 If `secure` is False you will connect with HTTP instead of
212 The value of `agent` is sent in the `X-Twitter-Client`
213 header. This is deprecated. Instead Twitter determines the
214 application using the OAuth Client Key and Client Key Secret
217 `api_version` is used to set the base uri. By default it's
218 nothing, but if you set it to '1' your URI will start with
224 if (format
not in ("json", "xml", "")):
225 raise ValueError("Unknown data format '%s'" %(format))
229 uriparts
+= (str(api_version
),)
231 TwitterCall
.__init
__(
232 self
, auth
=auth
, format
=format
, domain
=domain
,
233 secure
=secure
, uriparts
=uriparts
)
236 __all__
= ["Twitter", "TwitterError", "TwitterHTTPError"]