]>
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
):
53 kwargs
["source"] = self
.agent
56 if kwargs
.has_key('id'):
57 uri
+= "/%s" %(kwargs
['id'])
59 encoded_kwargs
= urlencode(kwargs
.items())
62 encoded_kwargs
= urlencode(kwargs
.items())
65 argStr
= "?%s" %(encoded_kwargs)
67 argData
= encoded_kwargs
71 headers
["X-Twitter-Client"] = self
.agent
73 headers
["Authorization"] = "Basic " + b64encode("%s:%s" %(
74 self
.username
, self
.password
))
76 req
= urllib2
.Request(
77 "http://%s/%s.%s%s" %(self
.domain
, self
.uri
, self
.format
, argStr
),
81 handle
= urllib2
.urlopen(req
)
82 if "json" == self
.format
:
83 return json
.loads(handle
.read())
86 except urllib2
.HTTPError
, e
:
91 "Twitter sent status %i for URL: %s.%s using parameters: (%s)\ndetails: %s" %(
92 e
.code
, uri
, self
.format
, encoded_kwargs
, e
.fp
.read()))
94 class Twitter(TwitterCall
):
96 The minimalist yet fully featured Twitter API class.
98 Get RESTful data by accessing members of this class. The result
99 is decoded python objects (lists and dicts).
101 The Twitter API is documented here:
103 http://apiwiki.twitter.com/
104 http://groups.google.com/group/twitter-development-talk/web/api-documentation
108 twitter = Twitter("hello@foo.com", "password123")
110 # Get the public timeline
111 twitter.statuses.public_timeline()
113 # Get a particular friend's timeline
114 twitter.statuses.friends_timeline(id="billybob")
116 # Also supported (but totally weird)
117 twitter.statuses.friends_timeline.billybob()
119 # Send a direct message
120 twitter.direct_messages.new(
122 text="I think yer swell!")
126 twitter_search = Twitter(domain="search.twitter.com")
128 # Find the latest search trends
129 twitter_search.trends()
131 # Search for the latest News on #gaza
132 twitter_search.search(q="#gaza")
134 Using the data returned::
136 Twitter API calls return decoded JSON. This is converted into
137 a bunch of Python lists, dicts, ints, and strings. For example,
139 x = twitter.statuses.public_timeline()
141 # The first 'tweet' in the timeline
144 # The screen name of the user who wrote the first 'tweet'
145 x[0]['user']['screen_name']
147 Getting raw XML data::
149 If you prefer to get your Twitter data in XML format, pass
150 format="xml" to the Twitter object when you instantiate it:
152 twitter = Twitter(format="xml")
154 The output will not be parsed in any way. It will be a raw string
158 self
, email
=None, password
=None, format
="json", domain
="twitter.com",
161 Create a new twitter API connector using the specified
162 credentials (email and password). Format specifies the output
163 format ("json" (default) or "xml").
165 if (format
not in ("json", "xml")):
166 raise TwitterError("Unknown data format '%s'" %(format))
167 TwitterCall
.__init
__(self
, email
, password
, format
, domain
, "", agent
)
169 __all__
= ["Twitter", "TwitterError"]