]> jfr.im git - z_archive/twitter.git/blame - twitter/api.py
Misc fixes for unicode
[z_archive/twitter.git] / twitter / api.py
CommitLineData
7364ea65 1
2from base64 import b64encode
5251ea48 3from urllib import urlencode
7364ea65 4
5import httplib
6import simplejson
7
5251ea48 8from exceptions import Exception
9
10class TwitterError(Exception):
11 pass
12
7364ea65 13class TwitterCall(object):
14 def __init__(self, username=None, password=None, uri=""):
15 self.username = username
16 self.password = password
17 self.uri = uri
18 def __getattr__(self, k):
19 try:
20 return object.__getattr__(self, k)
21 except AttributeError:
22 return TwitterCall(
23 self.username, self.password, self.uri + "/" + k)
24 def __call__(self, **kwargs):
25 method = "GET"
26 if self.uri.endswith('new') or self.uri.endswith('update'):
27 method = "POST"
28 argStr = ""
29 if kwargs:
5251ea48 30 argStr = "?" + urlencode(kwargs.items())
7364ea65 31 c = httplib.HTTPConnection("twitter.com")
32 try:
33 c.putrequest(method, "/%s.json%s" %(self.uri, argStr))
34 if (self.username):
35 c.putheader("Authorization", "Basic "
36 + b64encode("%s:%s" %(
37 self.username, self.password)))
38 c.endheaders()
39 r = c.getresponse()
40 if (r.status == 304):
41 return []
42 elif (r.status != 200):
5251ea48 43 raise TwitterError("Twitter sent status %i: %s" %(
7364ea65 44 r.status, r.read()))
45 return simplejson.loads(r.read())
46 finally:
47 c.close()
48
49class Twitter(TwitterCall):
50 """
51 The minimalist yet fully featured Twitter API class.
52
53 Get RESTful data by accessing members of this class. The result
54 is decoded python objects (lists and dicts).
55
56 The Twitter API is documented here:
57 http://groups.google.com/group/twitter-development-talk/web/api-documentation
58
59 Examples::
60
61 twitter = Twitter("hello@foo.com", "password123")
62
63 # Get the public timeline
64 twitter.statuses.public_timeline()
65
66 # Get a particular friend's timeline
67 twitter.statuses.friends_timeline(id="billybob")
68
69 # Also supported (but totally weird)
70 twitter.statuses.friends_timeline.billybob()
71
72 # Send a direct message
73 twitter.direct_messages.new(
74 user="billybob",
75 text="I think yer swell!")
76
77 Using the data returned::
78
79 Twitter API calls return decoded JSON. This is converted into
80 a bunch of Python lists, dicts, ints, and strings. For example,
81
82 x = twitter.statuses.public_timeline()
83
84 # The first 'tweet' in the timeline
85 x[0]
86
87 # The screen name of the user who wrote the first 'tweet'
88 x[0]['user']['screen_name']
89
90 """
91 def __init__(self, email=None, password=None):
92 """
93 Create a new twitter API connector using the specified
94 credentials (email and password).
95 """
96 TwitterCall.__init__(self, email, password)
97
98__all__ = ["Twitter"]