]>
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
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 self
.username
= username
31 self
.password
= password
36 def __getattr__(self
, k
):
38 return object.__getattr
__(self
, k
)
39 except AttributeError:
41 self
.username
, self
.password
, self
.format
, self
.domain
,
42 self
.uri
+ "/" + k
, self
.agent
)
43 def __call__(self
, **kwargs
):
46 for action
in _POST_ACTIONS
:
47 if self
.uri
.endswith(action
):
50 kwargs
["source"] = self
.agent
53 id = kwargs
.pop('id', None)
57 encoded_kwargs
= urlencode(kwargs
.items())
60 encoded_kwargs
= urlencode(kwargs
.items())
63 argStr
= "?%s" %(encoded_kwargs)
65 argData
= encoded_kwargs
69 headers
["X-Twitter-Client"] = self
.agent
71 headers
["Authorization"] = "Basic " + b64encode("%s:%s" %(
72 self
.username
, self
.password
))
74 req
= urllib2
.Request(
75 "http://%s/%s.%s%s" %(self
.domain
, self
.uri
, self
.format
, argStr
),
79 handle
= urllib2
.urlopen(req
)
80 if "json" == self
.format
:
81 return json
.loads(handle
.read())
84 except urllib2
.HTTPError
, e
:
89 "Twitter sent status %i for URL: %s.%s using parameters: (%s)\ndetails: %s" %(
90 e
.code
, uri
, self
.format
, encoded_kwargs
, e
.fp
.read()))
92 class Twitter(TwitterCall
):
94 The minimalist yet fully featured Twitter API class.
96 Get RESTful data by accessing members of this class. The result
97 is decoded python objects (lists and dicts).
99 The Twitter API is documented here:
101 http://apiwiki.twitter.com/
102 http://groups.google.com/group/twitter-development-talk/web/api-documentation
106 twitter = Twitter("hello@foo.com", "password123")
108 # Get the public timeline
109 twitter.statuses.public_timeline()
111 # Get a particular friend's timeline
112 twitter.statuses.friends_timeline(id="billybob")
114 # Also supported (but totally weird)
115 twitter.statuses.friends_timeline.billybob()
117 # Send a direct message
118 twitter.direct_messages.new(
120 text="I think yer swell!")
124 twitter_search = Twitter(domain="search.twitter.com")
126 # Find the latest search trends
127 twitter_search.trends()
129 # Search for the latest News on #gaza
130 twitter_search.search(q="#gaza")
132 Using the data returned::
134 Twitter API calls return decoded JSON. This is converted into
135 a bunch of Python lists, dicts, ints, and strings. For example,
137 x = twitter.statuses.public_timeline()
139 # The first 'tweet' in the timeline
142 # The screen name of the user who wrote the first 'tweet'
143 x[0]['user']['screen_name']
145 Getting raw XML data::
147 If you prefer to get your Twitter data in XML format, pass
148 format="xml" to the Twitter object when you instantiate it:
150 twitter = Twitter(format="xml")
152 The output will not be parsed in any way. It will be a raw string
156 self
, email
=None, password
=None, format
="json", domain
="twitter.com",
159 Create a new twitter API connector using the specified
160 credentials (email and password). Format specifies the output
161 format ("json" (default) or "xml").
163 if (format
not in ("json", "xml")):
164 raise TwitterError("Unknown data format '%s'" %(format))
165 TwitterCall
.__init
__(self
, email
, password
, format
, domain
, "", agent
)
167 __all__
= ["Twitter", "TwitterError"]