]>
jfr.im git - z_archive/twitter.git/blob - twitter/api.py
2 from base64
import b64encode
3 from urllib
import urlencode
7 from exceptions
import Exception
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 # These actions require POST http requests instead of GET
27 "create", "update", "destroy", "new", "follow", "leave",
30 class TwitterCall(object):
32 self
, username
, password
, format
, domain
, uri
="", agent
=None):
33 self
.username
= username
34 self
.password
= password
39 def __getattr__(self
, k
):
41 return object.__getattr
__(self
, k
)
42 except AttributeError:
44 self
.username
, self
.password
, self
.format
, self
.domain
,
45 self
.uri
+ "/" + k
, self
.agent
)
46 def __call__(self
, **kwargs
):
49 for action
in _POST_ACTIONS
:
50 if self
.uri
.endswith(action
):
54 kwargs
["source"] = self
.agent
56 if kwargs
.has_key('id'):
57 uri
+= "/%s" %(kwargs
['id'])
59 encoded_kwargs
= urlencode(kwargs
.items())
61 if kwargs
and (method
== "GET"):
62 argStr
= "?" + encoded_kwargs
66 headers
["X-Twitter-Client"] = self
.agent
68 headers
["Authorization"] = "Basic " + b64encode("%s:%s" %(
69 self
.username
, self
.password
))
71 headers
["Content-type"] = "application/x-www-form-urlencoded"
72 headers
["Content-length"] = len(encoded_kwargs
)
74 c
= httplib
.HTTPConnection(self
.domain
)
76 c
.putrequest(method
, "%s.%s%s" %(
77 uri
, self
.format
, argStr
))
78 for item
in headers
.iteritems():
82 c
.send(encoded_kwargs
)
87 elif (r
.status
!= 200):
89 "Twitter sent status %i for URL: %s.%s using parameters: (%s)\ndetails: %s" %(
90 r
.status
, uri
, self
.format
, encoded_kwargs
, r
.read()))
91 if "json" == self
.format
:
92 return json
.loads(r
.read())
98 class Twitter(TwitterCall
):
100 The minimalist yet fully featured Twitter API class.
102 Get RESTful data by accessing members of this class. The result
103 is decoded python objects (lists and dicts).
105 The Twitter API is documented here:
107 http://apiwiki.twitter.com/
108 http://groups.google.com/group/twitter-development-talk/web/api-documentation
112 twitter = Twitter("hello@foo.com", "password123")
114 # Get the public timeline
115 twitter.statuses.public_timeline()
117 # Get a particular friend's timeline
118 twitter.statuses.friends_timeline(id="billybob")
120 # Also supported (but totally weird)
121 twitter.statuses.friends_timeline.billybob()
123 # Send a direct message
124 twitter.direct_messages.new(
126 text="I think yer swell!")
130 twitter_search = Twitter(domain="search.twitter.com")
132 # Find the latest search trends
133 twitter_search.trends()
135 # Search for the latest News on #gaza
136 twitter_search.search(q="#gaza")
138 Using the data returned::
140 Twitter API calls return decoded JSON. This is converted into
141 a bunch of Python lists, dicts, ints, and strings. For example,
143 x = twitter.statuses.public_timeline()
145 # The first 'tweet' in the timeline
148 # The screen name of the user who wrote the first 'tweet'
149 x[0]['user']['screen_name']
151 Getting raw XML data::
153 If you prefer to get your Twitter data in XML format, pass
154 format="xml" to the Twitter object when you instantiate it:
156 twitter = Twitter(format="xml")
158 The output will not be parsed in any way. It will be a raw string
162 self
, email
=None, password
=None, format
="json", domain
="twitter.com",
165 Create a new twitter API connector using the specified
166 credentials (email and password). Format specifies the output
167 format ("json" (default) or "xml").
169 if (format
not in ("json", "xml")):
170 raise TwitterError("Unknown data format '%s'" %(format))
171 TwitterCall
.__init
__(self
, email
, password
, format
, domain
)
173 __all__
= ["Twitter", "TwitterError"]