]>
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):
26 def __init__(self
, username
, password
, format
, domain
, uri
=""):
27 self
.username
= username
28 self
.password
= password
32 def __getattr__(self
, k
):
34 return object.__getattr
__(self
, k
)
35 except AttributeError:
37 self
.username
, self
.password
, self
.format
, self
.domain
,
39 def __call__(self
, **kwargs
):
41 if (self
.uri
.endswith('new')
42 or self
.uri
.endswith('update')
43 or self
.uri
.endswith('create')
44 or self
.uri
.endswith('destroy')):
47 encoded_kwargs
= urlencode(kwargs
.items())
49 if kwargs
and (method
== "GET"):
50 argStr
= "?" + encoded_kwargs
54 headers
["Authorization"] = "Basic " + b64encode("%s:%s" %(
55 self
.username
, self
.password
))
57 headers
["Content-type"] = "application/x-www-form-urlencoded"
58 headers
["Content-length"] = len(encoded_kwargs
)
60 c
= httplib
.HTTPConnection(self
.domain
)
62 c
.putrequest(method
, "%s.%s%s" %(
63 self
.uri
, self
.format
, argStr
))
64 for item
in headers
.iteritems():
68 c
.send(encoded_kwargs
)
73 elif (r
.status
!= 200):
74 raise TwitterError("Twitter sent status %i: %s" %(
76 if "json" == self
.format
:
77 return json
.loads(r
.read())
83 class Twitter(TwitterCall
):
85 The minimalist yet fully featured Twitter API class.
87 Get RESTful data by accessing members of this class. The result
88 is decoded python objects (lists and dicts).
90 The Twitter API is documented here:
92 http://apiwiki.twitter.com/
93 http://groups.google.com/group/twitter-development-talk/web/api-documentation
97 twitter = Twitter("hello@foo.com", "password123")
99 # Get the public timeline
100 twitter.statuses.public_timeline()
102 # Get a particular friend's timeline
103 twitter.statuses.friends_timeline(id="billybob")
105 # Also supported (but totally weird)
106 twitter.statuses.friends_timeline.billybob()
108 # Send a direct message
109 twitter.direct_messages.new(
111 text="I think yer swell!")
115 twitter_search = Twitter(domain="search.twitter.com")
117 # Find the latest search trends
118 twitter_search.trends()
120 # Search for the latest News on #gaza
121 twitter_search.search(q="#gaza")
123 Using the data returned::
125 Twitter API calls return decoded JSON. This is converted into
126 a bunch of Python lists, dicts, ints, and strings. For example,
128 x = twitter.statuses.public_timeline()
130 # The first 'tweet' in the timeline
133 # The screen name of the user who wrote the first 'tweet'
134 x[0]['user']['screen_name']
136 Getting raw XML data::
138 If you prefer to get your Twitter data in XML format, pass
139 format="xml" to the Twitter object when you instantiate it:
141 twitter = Twitter(format="xml")
143 The output will not be parsed in any way. It will be a raw string
146 def __init__(self
, email
=None, password
=None, format
="json", domain
="twitter.com"):
148 Create a new twitter API connector using the specified
149 credentials (email and password). Format specifies the output
150 format ("json" (default) or "xml").
152 if (format
not in ("json", "xml")):
153 raise TwitterError("Unknown data format '%s'" %(format))
154 TwitterCall
.__init
__(self
, email
, password
, format
, domain
)
156 __all__
= ["Twitter", "TwitterError"]