]>
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
130 twitter = Twitter("hello@foo.com", "password123")
132 # Get the public timeline
133 twitter.statuses.public_timeline()
135 # Get a particular friend's timeline
136 twitter.statuses.friends_timeline(id="billybob")
138 # Also supported (but totally weird)
139 twitter.statuses.friends_timeline.billybob()
141 # Send a direct message
142 twitter.direct_messages.new(
144 text="I think yer swell!")
148 twitter_search = Twitter(domain="search.twitter.com")
150 # Find the latest search trends
151 twitter_search.trends()
153 # Search for the latest News on #gaza
154 twitter_search.search(q="#gaza")
157 Using the data returned
158 -----------------------
160 Twitter API calls return decoded JSON. This is converted into
161 a bunch of Python lists, dicts, ints, and strings. For example::
163 x = twitter.statuses.public_timeline()
165 # The first 'tweet' in the timeline
168 # The screen name of the user who wrote the first 'tweet'
169 x[0]['user']['screen_name']
175 If you prefer to get your Twitter data in XML format, pass
176 format="xml" to the Twitter object when you instantiate it::
178 twitter = Twitter(format="xml")
180 The output will not be parsed in any way. It will be a raw string
185 self
, email
=None, password
=None, format
="json",
186 domain
="api.twitter.com", agent
=None, secure
=True, auth
=None,
189 Create a new twitter API connector.
191 Pass an `auth` parameter to use the credentials of a specific
192 user. Generally you'll want to pass an `OAuth`
193 instance. Alternately you can pass `email` and `password`
194 parameters but this authentication mode will be deactive by
195 Twitter in the future and is not recommended.
197 `domain` lets you change the domain you are connecting. By
198 default it's twitter.com but `search.twitter.com` may be
201 If `secure` is False you will connect with HTTP instead of
204 The value of `agent` is sent in the `X-Twitter-Client`
205 header. This is deprecated. Instead Twitter determines the
206 application using the OAuth Client Key and Client Key Secret
210 if email
is not None or password
is not None:
213 "Can't specify 'email'/'password' and 'auth' params"
215 auth
= UserPassAuth(email
, password
)
220 if (format
not in ("json", "xml", "")):
221 raise ValueError("Unknown data format '%s'" %(format))
225 uri
= str(api_version
)
227 TwitterCall
.__init
__(
228 self
, auth
, format
, domain
, uri
, agent
,
231 __all__
= ["Twitter", "TwitterError", "TwitterHTTPError"]