]>
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 class TwitterCall(object):
27 self
, username
, password
, format
, domain
, uri
="", agent
="twitter.py"
29 self
.username
= username
30 self
.password
= password
35 def __getattr__(self
, k
):
37 return object.__getattr
__(self
, k
)
38 except AttributeError:
40 self
.username
, self
.password
, self
.format
, self
.domain
,
41 self
.uri
+ "/" + k
, self
.agent
43 def __call__(self
, **kwargs
):
45 if (self
.uri
.endswith('new')
46 or self
.uri
.endswith('update')
47 or self
.uri
.endswith('create')
48 or self
.uri
.endswith('destroy')):
51 kwargs
["source"] = self
.agent
53 encoded_kwargs
= urlencode(kwargs
.items())
55 if kwargs
and (method
== "GET"):
56 argStr
= "?" + encoded_kwargs
60 headers
["X-Twitter-Client"] = self
.agent
62 headers
["Authorization"] = "Basic " + b64encode("%s:%s" %(
63 self
.username
, self
.password
))
65 headers
["Content-type"] = "application/x-www-form-urlencoded"
66 headers
["Content-length"] = len(encoded_kwargs
)
68 c
= httplib
.HTTPConnection(self
.domain
)
70 c
.putrequest(method
, "%s.%s%s" %(
71 self
.uri
, self
.format
, argStr
))
72 for item
in headers
.iteritems():
76 c
.send(encoded_kwargs
)
81 elif (r
.status
!= 200):
82 raise TwitterError("Twitter sent status %i: %s" %(
84 if "json" == self
.format
:
85 return json
.loads(r
.read())
91 class Twitter(TwitterCall
):
93 The minimalist yet fully featured Twitter API class.
95 Get RESTful data by accessing members of this class. The result
96 is decoded python objects (lists and dicts).
98 The Twitter API is documented here:
100 http://apiwiki.twitter.com/
101 http://groups.google.com/group/twitter-development-talk/web/api-documentation
105 twitter = Twitter("hello@foo.com", "password123")
107 # Get the public timeline
108 twitter.statuses.public_timeline()
110 # Get a particular friend's timeline
111 twitter.statuses.friends_timeline(id="billybob")
113 # Also supported (but totally weird)
114 twitter.statuses.friends_timeline.billybob()
116 # Send a direct message
117 twitter.direct_messages.new(
119 text="I think yer swell!")
123 twitter_search = Twitter(domain="search.twitter.com")
125 # Find the latest search trends
126 twitter_search.trends()
128 # Search for the latest News on #gaza
129 twitter_search.search(q="#gaza")
131 Using the data returned::
133 Twitter API calls return decoded JSON. This is converted into
134 a bunch of Python lists, dicts, ints, and strings. For example,
136 x = twitter.statuses.public_timeline()
138 # The first 'tweet' in the timeline
141 # The screen name of the user who wrote the first 'tweet'
142 x[0]['user']['screen_name']
144 Getting raw XML data::
146 If you prefer to get your Twitter data in XML format, pass
147 format="xml" to the Twitter object when you instantiate it:
149 twitter = Twitter(format="xml")
151 The output will not be parsed in any way. It will be a raw string
154 def __init__(self
, email
=None, password
=None, format
="json", domain
="twitter.com"):
156 Create a new twitter API connector using the specified
157 credentials (email and password). Format specifies the output
158 format ("json" (default) or "xml").
160 if (format
not in ("json", "xml")):
161 raise TwitterError("Unknown data format '%s'" %(format))
162 TwitterCall
.__init
__(self
, email
, password
, format
, domain
)
164 __all__
= ["Twitter", "TwitterError"]