]> jfr.im git - z_archive/twitter.git/blob - twitter/api.py
Remove agent cruft. Default to api.twitter.com and version 1.
[z_archive/twitter.git] / twitter / api.py
1 try:
2 import urllib.request as urllib_request
3 import urllib.error as urllib_error
4 except ImportError:
5 import urllib2 as urllib_request
6 import urllib2 as urllib_error
7
8 from twitter.twitter_globals import POST_ACTIONS
9 from twitter.auth import NoAuth
10
11 def _py26OrGreater():
12 import sys
13 return sys.hexversion > 0x20600f0
14
15 if _py26OrGreater():
16 import json
17 else:
18 import simplejson as json
19
20 class TwitterError(Exception):
21 """
22 Base Exception thrown by the Twitter object when there is a
23 general error interacting with the API.
24 """
25 pass
26
27 class TwitterHTTPError(TwitterError):
28 """
29 Exception thrown by the Twitter object when there is an
30 HTTP error interacting with twitter.com.
31 """
32 def __init__(self, e, uri, format, uriparts):
33 self.e = e
34 self.uri = uri
35 self.format = format
36 self.uriparts = uriparts
37
38 def __str__(self):
39 return (
40 "Twitter sent status %i for URL: %s.%s using parameters: "
41 "(%s)\ndetails: %s" %(
42 self.e.code, self.uri, self.format, self.uriparts,
43 self.e.fp.read()))
44
45 class TwitterResponse(object):
46 """
47 Response from a twitter request. Behaves like a list or a string
48 (depending on requested format) but it has a few other interesting
49 attributes.
50
51 `headers` gives you access to the response headers as an
52 httplib.HTTPHeaders instance. You can do
53 `response.headers.getheader('h')` to retrieve a header.
54 """
55 def __init__(self, headers):
56 self.headers = headers
57
58 @property
59 def rate_limit_remaining(self):
60 """
61 Remaining requests in the current rate-limit.
62 """
63 return int(self.headers.getheader('X-RateLimit-Remaining'))
64
65 @property
66 def rate_limit_reset(self):
67 """
68 Time in UTC epoch seconds when the rate limit will reset.
69 """
70 return int(self.headers.getheader('X-RateLimit-Reset'))
71
72
73 def wrap_response(response, headers):
74 response_typ = type(response)
75 if response_typ is bool:
76 # HURF DURF MY NAME IS PYTHON AND I CAN'T SUBCLASS bool.
77 response_typ = int
78
79 class WrappedTwitterResponse(response_typ, TwitterResponse):
80 __doc__ = TwitterResponse.__doc__
81
82 def __init__(self, response):
83 if response_typ is not int:
84 response_typ.__init__(self, response)
85 TwitterResponse.__init__(self, headers)
86
87 return WrappedTwitterResponse(response)
88
89
90
91 class TwitterCall(object):
92 def __init__(
93 self, auth, format, domain, uri="",
94 uriparts=None, secure=True):
95 self.auth = auth
96 self.format = format
97 self.domain = domain
98 self.uri = uri
99 self.uriparts = uriparts
100 self.secure = secure
101
102 def __getattr__(self, k):
103 try:
104 return object.__getattr__(self, k)
105 except AttributeError:
106 return TwitterCall(
107 auth=self.auth, format=self.format, domain=self.domain,
108 uriparts=self.uriparts + (k,),
109 secure=self.secure)
110
111 def __call__(self, **kwargs):
112 # Build the uri.
113 uriparts = []
114 for uripart in self.uriparts:
115 # If this part matches a keyword argument, use the
116 # supplied value otherwise, just use the part.
117 uriparts.append(str(kwargs.pop(uripart, uripart)))
118 uri = '/'.join(uriparts)
119
120 method = "GET"
121 for action in POST_ACTIONS:
122 if uri.endswith(action):
123 method = "POST"
124 break
125
126 # If an id kwarg is present and there is no id to fill in in
127 # the list of uriparts, assume the id goes at the end.
128 id = kwargs.pop('id', None)
129 if id:
130 uri += "/%s" %(id)
131
132 secure_str = ''
133 if self.secure:
134 secure_str = 's'
135 dot = ""
136 if self.format:
137 dot = "."
138 uriBase = "http%s://%s/%s%s%s" %(
139 secure_str, self.domain, uri, dot, self.format)
140
141 headers = {}
142 if self.auth:
143 headers.update(self.auth.generate_headers())
144 arg_data = self.auth.encode_params(uriBase, method, kwargs)
145 if method == 'GET':
146 uriBase += '?' + arg_data
147 body = None
148 else:
149 body = arg_data.encode('utf8')
150
151 req = urllib_request.Request(uriBase, body, headers)
152
153 try:
154 handle = urllib_request.urlopen(req)
155 if "json" == self.format:
156 res = json.loads(handle.read().decode('utf8'))
157 return wrap_response(res, handle.headers)
158 else:
159 return wrap_response(
160 handle.read().decode('utf8'), handle.headers)
161 except urllib_error.HTTPError as e:
162 if (e.code == 304):
163 return []
164 else:
165 raise TwitterHTTPError(e, uri, self.format, arg_data)
166
167 class Twitter(TwitterCall):
168 """
169 The minimalist yet fully featured Twitter API class.
170
171 Get RESTful data by accessing members of this class. The result
172 is decoded python objects (lists and dicts).
173
174 The Twitter API is documented here:
175
176 http://dev.twitter.com/doc
177
178
179 Examples::
180
181 twitter = Twitter(
182 auth=OAuth(token, token_key, con_secret, con_secret_key)))
183
184 # Get the public timeline
185 twitter.statuses.public_timeline()
186
187 # Get a particular friend's timeline
188 twitter.statuses.friends_timeline(id="billybob")
189
190 # Also supported (but totally weird)
191 twitter.statuses.friends_timeline.billybob()
192
193 # Send a direct message
194 twitter.direct_messages.new(
195 user="billybob",
196 text="I think yer swell!")
197
198 # Get the members of a particular list of a particular friend
199 twitter.user.listname.members(user="billybob", listname="billysbuds")
200
201
202 Searching Twitter::
203
204 twitter_search = Twitter(domain="search.twitter.com")
205
206 # Find the latest search trends
207 twitter_search.trends()
208
209 # Search for the latest News on #gaza
210 twitter_search.search(q="#gaza")
211
212
213 Using the data returned
214 -----------------------
215
216 Twitter API calls return decoded JSON. This is converted into
217 a bunch of Python lists, dicts, ints, and strings. For example::
218
219 x = twitter.statuses.public_timeline()
220
221 # The first 'tweet' in the timeline
222 x[0]
223
224 # The screen name of the user who wrote the first 'tweet'
225 x[0]['user']['screen_name']
226
227
228 Getting raw XML data
229 --------------------
230
231 If you prefer to get your Twitter data in XML format, pass
232 format="xml" to the Twitter object when you instantiate it::
233
234 twitter = Twitter(format="xml")
235
236 The output will not be parsed in any way. It will be a raw string
237 of XML.
238
239 """
240 def __init__(
241 self, format="json",
242 domain="api.twitter.com", secure=True, auth=None,
243 api_version='1'):
244 """
245 Create a new twitter API connector.
246
247 Pass an `auth` parameter to use the credentials of a specific
248 user. Generally you'll want to pass an `OAuth`
249 instance::
250
251 twitter = Twitter(auth=OAuth(
252 token, token_secret, consumer_key, consumer_secret))
253
254
255 `domain` lets you change the domain you are connecting. By
256 default it's `api.twitter.com` but `search.twitter.com` may be
257 useful too.
258
259 If `secure` is False you will connect with HTTP instead of
260 HTTPS.
261
262 `api_version` is used to set the base uri. By default it's
263 '1'.
264 """
265 if not auth:
266 auth = NoAuth()
267
268 if (format not in ("json", "xml", "")):
269 raise ValueError("Unknown data format '%s'" %(format))
270
271 uriparts = ()
272 if api_version:
273 uriparts += (str(api_version),)
274
275 TwitterCall.__init__(
276 self, auth=auth, format=format, domain=domain,
277 secure=secure, uriparts=uriparts)
278
279
280 __all__ = ["Twitter", "TwitterError", "TwitterHTTPError", "TwitterResponse"]