]>
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
="",
28 agent
="Python Twitter Tools"
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
44 def __call__(self
, **kwargs
):
46 if (self
.uri
.endswith('new')
47 or self
.uri
.endswith('update')
48 or self
.uri
.endswith('create')
49 or self
.uri
.endswith('destroy')):
52 kwargs
["source"] = self
.agent
54 encoded_kwargs
= urlencode(kwargs
.items())
56 if kwargs
and (method
== "GET"):
57 argStr
= "?" + encoded_kwargs
61 headers
["X-Twitter-Client"] = self
.agent
63 headers
["Authorization"] = "Basic " + b64encode("%s:%s" %(
64 self
.username
, self
.password
))
66 headers
["Content-type"] = "application/x-www-form-urlencoded"
67 headers
["Content-length"] = len(encoded_kwargs
)
69 c
= httplib
.HTTPConnection(self
.domain
)
71 c
.putrequest(method
, "%s.%s%s" %(
72 self
.uri
, self
.format
, argStr
))
73 for item
in headers
.iteritems():
77 c
.send(encoded_kwargs
)
82 elif (r
.status
!= 200):
83 raise TwitterError("Twitter sent status %i: %s" %(
85 if "json" == self
.format
:
86 return json
.loads(r
.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
155 def __init__(self
, email
=None, password
=None, format
="json", domain
="twitter.com"):
157 Create a new twitter API connector using the specified
158 credentials (email and password). Format specifies the output
159 format ("json" (default) or "xml").
161 if (format
not in ("json", "xml")):
162 raise TwitterError("Unknown data format '%s'" %(format))
163 TwitterCall
.__init
__(self
, email
, password
, format
, domain
)
165 __all__
= ["Twitter", "TwitterError"]