]>
jfr.im git - z_archive/twitter.git/blob - twitter/api.py
2 from base64
import encodestring
3 from urllib
import urlencode
7 from exceptions
import Exception
9 from twitter
.twitter_globals
import POST_ACTIONS
13 return sys
.hexversion
> 0x20600f0
18 import simplejson
as json
20 class TwitterError(Exception):
22 Exception thrown by the Twitter object when there is an
23 error interacting with twitter.com.
27 class TwitterCall(object):
29 self
, username
, password
, format
, domain
, uri
="", agent
=None,
30 encoded_args
=None, secure
=True):
31 self
.username
= username
32 self
.password
= password
37 self
.encoded_args
= encoded_args
40 def __getattr__(self
, k
):
42 return object.__getattr
__(self
, k
)
43 except AttributeError:
45 self
.username
, self
.password
, self
.format
, self
.domain
,
46 self
.uri
+ "/" + k
, self
.agent
, self
.encoded_args
)
48 def __call__(self
, **kwargs
):
51 for action
in POST_ACTIONS
:
52 if self
.uri
.endswith(action
):
55 kwargs
["source"] = self
.agent
58 if (not self
.encoded_args
):
59 if kwargs
.has_key('id'):
60 uri
+= "/%s" %(kwargs
['id'])
62 self
.encoded_args
= urlencode(kwargs
.items())
68 argStr
= "?%s" %(self
.encoded_args
)
70 argData
= self
.encoded_args
74 headers
["X-Twitter-Client"] = self
.agent
76 headers
["Authorization"] = "Basic " + encodestring("%s:%s" %(
77 self
.username
, self
.password
)).strip('\n')
83 req
= urllib2
.Request(
84 "http%s://%s/%s.%s%s" %(
85 secure_str
, self
.domain
, uri
, self
.format
, argStr
),
89 handle
= urllib2
.urlopen(req
)
90 if "json" == self
.format
:
91 return json
.loads(handle
.read())
94 except urllib2
.HTTPError
, e
:
99 "Twitter sent status %i for URL: %s.%s using parameters: (%s)\ndetails: %s" %(
100 e
.code
, uri
, self
.format
, encoded_kwargs
, e
.fp
.read()))
102 class Twitter(TwitterCall
):
104 The minimalist yet fully featured Twitter API class.
106 Get RESTful data by accessing members of this class. The result
107 is decoded python objects (lists and dicts).
109 The Twitter API is documented here:
111 http://apiwiki.twitter.com/
112 http://groups.google.com/group/twitter-development-talk/web/api-documentation
116 twitter = Twitter("hello@foo.com", "password123")
118 # Get the public timeline
119 twitter.statuses.public_timeline()
121 # Get a particular friend's timeline
122 twitter.statuses.friends_timeline(id="billybob")
124 # Also supported (but totally weird)
125 twitter.statuses.friends_timeline.billybob()
127 # Send a direct message
128 twitter.direct_messages.new(
130 text="I think yer swell!")
134 twitter_search = Twitter(domain="search.twitter.com")
136 # Find the latest search trends
137 twitter_search.trends()
139 # Search for the latest News on #gaza
140 twitter_search.search(q="#gaza")
142 Using the data returned::
144 Twitter API calls return decoded JSON. This is converted into
145 a bunch of Python lists, dicts, ints, and strings. For example,
147 x = twitter.statuses.public_timeline()
149 # The first 'tweet' in the timeline
152 # The screen name of the user who wrote the first 'tweet'
153 x[0]['user']['screen_name']
155 Getting raw XML data::
157 If you prefer to get your Twitter data in XML format, pass
158 format="xml" to the Twitter object when you instantiate it:
160 twitter = Twitter(format="xml")
162 The output will not be parsed in any way. It will be a raw string
166 self
, email
=None, password
=None, format
="json", domain
="twitter.com",
167 agent
=None, secure
=True):
169 Create a new twitter API connector using the specified
170 credentials (email and password). Format specifies the output
171 format ("json" (default) or "xml").
173 if (format
not in ("json", "xml")):
174 raise TwitterError("Unknown data format '%s'" %(format))
175 TwitterCall
.__init
__(
176 self
, email
, password
, format
, domain
, "", agent
,
179 __all__
= ["Twitter", "TwitterError"]