]>
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
11 return sys
.hexversion
> 0x20600f0
16 import simplejson
as json
18 class TwitterError(Exception):
20 Exception thrown by the Twitter object when there is an
21 error interacting with twitter.com.
25 class TwitterCall(object):
27 self
, auth
, format
, domain
, uri
="", agent
=None,
28 encoded_args
=None, secure
=True):
34 self
.encoded_args
= encoded_args
37 def __getattr__(self
, k
):
39 return object.__getattr
__(self
, k
)
40 except AttributeError:
42 self
.auth
, self
.format
, self
.domain
,
43 self
.uri
+ "/" + k
, self
.agent
, self
.encoded_args
, self
.secure
)
45 def __call__(self
, **kwargs
):
46 uri
= self
.uri
.strip("/")
48 for action
in POST_ACTIONS
:
49 if self
.uri
.endswith(action
):
52 kwargs
["source"] = self
.agent
58 uriBase
= "http%s://%s/%s.%s" %(
59 secure_str
, self
.domain
, uri
, self
.format
)
61 if (not self
.encoded_args
):
62 if kwargs
.has_key('id'):
63 uri
+= "/%s" %(kwargs
['id'])
65 self
.encoded_args
= self
.auth
.encode_params(uriBase
, method
, kwargs
)
71 argStr
= "?%s" %(self
.encoded_args
)
73 argData
= self
.encoded_args
77 headers
["X-Twitter-Client"] = self
.agent
78 if self
.auth
is not None:
79 headers
.update(self
.auth
.generate_headers())
81 req
= urllib2
.Request(uriBase
+argStr
, argData
, headers
)
84 handle
= urllib2
.urlopen(req
)
85 if "json" == self
.format
:
86 return json
.loads(handle
.read())
89 except urllib2
.HTTPError
, e
:
94 "Twitter sent status %i for URL: %s.%s using parameters: (%s)\ndetails: %s" %(
95 e
.code
, uri
, self
.format
, self
.encoded_args
, e
.fp
.read()))
97 class Twitter(TwitterCall
):
99 The minimalist yet fully featured Twitter API class.
101 Get RESTful data by accessing members of this class. The result
102 is decoded python objects (lists and dicts).
104 The Twitter API is documented here:
106 http://apiwiki.twitter.com/
107 http://groups.google.com/group/twitter-development-talk/web/api-documentation
111 twitter = Twitter("hello@foo.com", "password123")
113 # Get the public timeline
114 twitter.statuses.public_timeline()
116 # Get a particular friend's timeline
117 twitter.statuses.friends_timeline(id="billybob")
119 # Also supported (but totally weird)
120 twitter.statuses.friends_timeline.billybob()
122 # Send a direct message
123 twitter.direct_messages.new(
125 text="I think yer swell!")
129 twitter_search = Twitter(domain="search.twitter.com")
131 # Find the latest search trends
132 twitter_search.trends()
134 # Search for the latest News on #gaza
135 twitter_search.search(q="#gaza")
137 Using the data returned::
139 Twitter API calls return decoded JSON. This is converted into
140 a bunch of Python lists, dicts, ints, and strings. For example,
142 x = twitter.statuses.public_timeline()
144 # The first 'tweet' in the timeline
147 # The screen name of the user who wrote the first 'tweet'
148 x[0]['user']['screen_name']
150 Getting raw XML data::
152 If you prefer to get your Twitter data in XML format, pass
153 format="xml" to the Twitter object when you instantiate it:
155 twitter = Twitter(format="xml")
157 The output will not be parsed in any way. It will be a raw string
161 self
, email
=None, password
=None, format
="json", domain
="twitter.com",
162 agent
=None, secure
=True, auth
=None):
164 Create a new twitter API connector using the specified
165 credentials (email and password). Format specifies the output
166 format ("json" (default) or "xml").
169 if email
is not None or password
is not None:
171 raise ValueError, "can't specify 'email' or 'password' and 'auth' params"
172 auth
= UserPassAuth(email
, password
)
174 if (format
not in ("json", "xml")):
175 raise TwitterError("Unknown data format '%s'" %(format))
176 TwitterCall
.__init
__(
177 self
, auth
, format
, domain
, "", agent
,
180 __all__
= ["Twitter", "TwitterError"]