]>
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 class TwitterError(Exception):
12 class TwitterCall(object):
13 def __init__(self
, username
, password
, format
, uri
=""):
14 self
.username
= username
15 self
.password
= password
18 def __getattr__(self
, k
):
20 return object.__getattr
__(self
, k
)
21 except AttributeError:
23 self
.username
, self
.password
, self
.format
,
25 def __call__(self
, **kwargs
):
27 if self
.uri
.endswith('new') or self
.uri
.endswith('update'):
31 argStr
= "?" + urlencode(kwargs
.items())
32 c
= httplib
.HTTPConnection("twitter.com")
34 c
.putrequest(method
, "/%s.%s%s" %(
35 self
.uri
, self
.format
, argStr
))
38 "Authorization", "Basic " + b64encode("%s:%s" %(
39 self
.username
, self
.password
)))
40 if (method
== "POST"):
41 # TODO specify charset
47 elif (r
.status
!= 200):
48 raise TwitterError("Twitter sent status %i: %s" %(
50 if ("json" == self
.format
):
52 return simplejson
.loads(r
.read())
58 class Twitter(TwitterCall
):
60 The minimalist yet fully featured Twitter API class.
62 Get RESTful data by accessing members of this class. The result
63 is decoded python objects (lists and dicts).
65 The Twitter API is documented here:
66 http://groups.google.com/group/twitter-development-talk/web/api-documentation
70 twitter = Twitter("hello@foo.com", "password123")
72 # Get the public timeline
73 twitter.statuses.public_timeline()
75 # Get a particular friend's timeline
76 twitter.statuses.friends_timeline(id="billybob")
78 # Also supported (but totally weird)
79 twitter.statuses.friends_timeline.billybob()
81 # Send a direct message
82 twitter.direct_messages.new(
84 text="I think yer swell!")
86 Using the data returned::
88 Twitter API calls return decoded JSON. This is converted into
89 a bunch of Python lists, dicts, ints, and strings. For example,
91 x = twitter.statuses.public_timeline()
93 # The first 'tweet' in the timeline
96 # The screen name of the user who wrote the first 'tweet'
97 x[0]['user']['screen_name']
99 Getting raw XML data::
101 If you prefer to get your Twitter data in XML format, pass
102 format="xml" to the Twitter object when you instantiate it:
104 twitter = Twitter(format="xml")
106 The output will not be parsed in any way. It will be a raw string
109 def __init__(self
, email
=None, password
=None, format
="json"):
111 Create a new twitter API connector using the specified
112 credentials (email and password). Format specifies the output
113 format ("json" (default) or "xml").
115 if (format
not in ("json", "xml")):
116 raise TwitterError("Unknown data format '%s'" %(format))
117 if (format
== "json"):
122 "format not available: simplejson is not installed")
123 TwitterCall
.__init
__(self
, email
, password
, format
)
125 __all__
= ["Twitter"]