]>
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
37 return "Twitter sent status %i for URL: %s.%s using parameters: (%s)\ndetails: %s" %(
38 self
.e
.code
, self
.uri
, self
.format
, self
.encoded_args
, self
.e
.fp
.read())
40 class TwitterCall(object):
42 self
, auth
, format
, domain
, uri
="", agent
=None,
43 encoded_args
=None, secure
=True):
49 self
.encoded_args
= encoded_args
52 def __getattr__(self
, k
):
54 return object.__getattr
__(self
, k
)
55 except AttributeError:
57 self
.auth
, self
.format
, self
.domain
,
58 self
.uri
+ "/" + k
, self
.agent
, self
.encoded_args
, self
.secure
)
60 def __call__(self
, **kwargs
):
61 uri
= self
.uri
.strip("/")
63 for action
in POST_ACTIONS
:
64 if self
.uri
.endswith(action
):
67 kwargs
["source"] = self
.agent
76 uriBase
= "http%s://%s/%s%s%s" %(
77 secure_str
, self
.domain
, uri
, dot
, self
.format
)
79 if (not self
.encoded_args
):
80 if kwargs
.has_key('id'):
81 uri
+= "/%s" %(kwargs
['id'])
83 self
.encoded_args
= self
.auth
.encode_params(uriBase
, method
, kwargs
)
89 argStr
= "?%s" %(self
.encoded_args
)
91 argData
= self
.encoded_args
95 headers
["X-Twitter-Client"] = self
.agent
96 if self
.auth
is not None:
97 headers
.update(self
.auth
.generate_headers())
99 req
= urllib2
.Request(uriBase
+argStr
, argData
, headers
)
102 handle
= urllib2
.urlopen(req
)
103 if "json" == self
.format
:
104 return json
.loads(handle
.read())
107 except urllib2
.HTTPError
, e
:
111 raise TwitterHTTPError(e
, uri
, self
.format
, self
.encoded_args
)
113 class Twitter(TwitterCall
):
115 The minimalist yet fully featured Twitter API class.
117 Get RESTful data by accessing members of this class. The result
118 is decoded python objects (lists and dicts).
120 The Twitter API is documented here:
122 http://apiwiki.twitter.com/
123 http://groups.google.com/group/twitter-development-talk/web/api-documentation
127 twitter = Twitter("hello@foo.com", "password123")
129 # Get the public timeline
130 twitter.statuses.public_timeline()
132 # Get a particular friend's timeline
133 twitter.statuses.friends_timeline(id="billybob")
135 # Also supported (but totally weird)
136 twitter.statuses.friends_timeline.billybob()
138 # Send a direct message
139 twitter.direct_messages.new(
141 text="I think yer swell!")
145 twitter_search = Twitter(domain="search.twitter.com")
147 # Find the latest search trends
148 twitter_search.trends()
150 # Search for the latest News on #gaza
151 twitter_search.search(q="#gaza")
153 Using the data returned::
155 Twitter API calls return decoded JSON. This is converted into
156 a bunch of Python lists, dicts, ints, and strings. For example,
158 x = twitter.statuses.public_timeline()
160 # The first 'tweet' in the timeline
163 # The screen name of the user who wrote the first 'tweet'
164 x[0]['user']['screen_name']
166 Getting raw XML data::
168 If you prefer to get your Twitter data in XML format, pass
169 format="xml" to the Twitter object when you instantiate it:
171 twitter = Twitter(format="xml")
173 The output will not be parsed in any way. It will be a raw string
177 self
, email
=None, password
=None, format
="json", domain
="twitter.com",
178 agent
=None, secure
=True, auth
=None):
180 Create a new twitter API connector using the specified
181 credentials (email and password). Format specifies the output
182 format ("json" (default) or "xml").
185 if email
is not None or password
is not None:
187 raise ValueError, "can't specify 'email' or 'password' and 'auth' params"
188 auth
= UserPassAuth(email
, password
)
193 if (format
not in ("json", "xml", "")):
194 raise TwitterError("Unknown data format '%s'" %(format))
195 TwitterCall
.__init
__(
196 self
, auth
, format
, domain
, "", agent
,
199 __all__
= ["Twitter", "TwitterError", "TwitterHTTPError"]