]>
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 id = kwargs
.pop('id', None)
60 encoded_kwargs
= urlencode(kwargs
.items())
63 encoded_kwargs
= urlencode(kwargs
.items())
66 argStr
= "?%s" %(encoded_kwargs)
68 argData
= encoded_kwargs
72 headers
["X-Twitter-Client"] = self
.agent
74 headers
["Authorization"] = "Basic " + b64encode("%s:%s" %(
75 self
.username
, self
.password
))
77 req
= urllib2
.Request(
78 "http://%s/%s.%s%s" %(self
.domain
, self
.uri
, self
.format
, argStr
),
82 handle
= urllib2
.urlopen(req
)
83 if "json" == self
.format
:
84 return json
.loads(handle
.read())
87 except urllib2
.HTTPError
, e
:
92 "Twitter sent status %i for URL: %s.%s using parameters: (%s)\ndetails: %s" %(
93 e
.code
, uri
, self
.format
, encoded_kwargs
, e
,msg
))
95 class Twitter(TwitterCall
):
97 The minimalist yet fully featured Twitter API class.
99 Get RESTful data by accessing members of this class. The result
100 is decoded python objects (lists and dicts).
102 The Twitter API is documented here:
104 http://apiwiki.twitter.com/
105 http://groups.google.com/group/twitter-development-talk/web/api-documentation
109 twitter = Twitter("hello@foo.com", "password123")
111 # Get the public timeline
112 twitter.statuses.public_timeline()
114 # Get a particular friend's timeline
115 twitter.statuses.friends_timeline(id="billybob")
117 # Also supported (but totally weird)
118 twitter.statuses.friends_timeline.billybob()
120 # Send a direct message
121 twitter.direct_messages.new(
123 text="I think yer swell!")
127 twitter_search = Twitter(domain="search.twitter.com")
129 # Find the latest search trends
130 twitter_search.trends()
132 # Search for the latest News on #gaza
133 twitter_search.search(q="#gaza")
135 Using the data returned::
137 Twitter API calls return decoded JSON. This is converted into
138 a bunch of Python lists, dicts, ints, and strings. For example,
140 x = twitter.statuses.public_timeline()
142 # The first 'tweet' in the timeline
145 # The screen name of the user who wrote the first 'tweet'
146 x[0]['user']['screen_name']
148 Getting raw XML data::
150 If you prefer to get your Twitter data in XML format, pass
151 format="xml" to the Twitter object when you instantiate it:
153 twitter = Twitter(format="xml")
155 The output will not be parsed in any way. It will be a raw string
159 self
, email
=None, password
=None, format
="json", domain
="twitter.com",
162 Create a new twitter API connector using the specified
163 credentials (email and password). Format specifies the output
164 format ("json" (default) or "xml").
166 if (format
not in ("json", "xml")):
167 raise TwitterError("Unknown data format '%s'" %(format))
168 TwitterCall
.__init
__(self
, email
, password
, format
, domain
, "", agent
)
170 __all__
= ["Twitter", "TwitterError"]