]> jfr.im git - z_archive/twitter.git/blob - twitter/api.py
Merge commit 'origin/api_update_docfix'
[z_archive/twitter.git] / twitter / api.py
1
2 from base64 import b64encode
3 from urllib import urlencode
4
5 import urllib2
6
7 from exceptions import Exception
8
9 from twitter.twitter_globals import POST_ACTIONS
10
11 def _py26OrGreater():
12 import sys
13 return sys.hexversion > 0x20600f0
14
15 if _py26OrGreater():
16 import json
17 else:
18 import simplejson as json
19
20 class TwitterError(Exception):
21 """
22 Exception thrown by the Twitter object when there is an
23 error interacting with twitter.com.
24 """
25 pass
26
27 class TwitterCall(object):
28 def __init__(
29 self, username, password, format, domain, uri="", agent=None):
30 self.username = username
31 self.password = password
32 self.format = format
33 self.domain = domain
34 self.uri = uri
35 self.agent = agent
36 def __getattr__(self, k):
37 try:
38 return object.__getattr__(self, k)
39 except AttributeError:
40 return TwitterCall(
41 self.username, self.password, self.format, self.domain,
42 self.uri + "/" + k, self.agent)
43 def __call__(self, **kwargs):
44 uri = self.uri
45 method = "GET"
46 for action in POST_ACTIONS:
47 if self.uri.endswith(action):
48 method = "POST"
49 if (self.agent):
50 kwargs["source"] = self.agent
51 break
52
53 id = kwargs.pop('id', None)
54 if id:
55 uri += "/%s" %(id)
56
57 argStr = ""
58 argData = None
59 encoded_kwargs = urlencode(kwargs.items())
60 if (method == "GET"):
61 if kwargs:
62 argStr = "?%s" %(encoded_kwargs)
63 else:
64 argData = encoded_kwargs
65
66 headers = {}
67 if (self.agent):
68 headers["X-Twitter-Client"] = self.agent
69 if (self.username):
70 headers["Authorization"] = "Basic " + b64encode("%s:%s" %(
71 self.username, self.password))
72
73 req = urllib2.Request(
74 "http://%s/%s.%s%s" %(self.domain, uri, self.format, argStr),
75 argData, headers
76 )
77 try:
78 handle = urllib2.urlopen(req)
79 if "json" == self.format:
80 return json.loads(handle.read())
81 else:
82 return handle.read()
83 except urllib2.HTTPError, e:
84 if (e.code == 304):
85 return []
86 else:
87 raise TwitterError(
88 "Twitter sent status %i for URL: %s.%s using parameters: (%s)\ndetails: %s" %(
89 e.code, uri, self.format, encoded_kwargs, e.fp.read()))
90
91 class Twitter(TwitterCall):
92 """
93 The minimalist yet fully featured Twitter API class.
94
95 Get RESTful data by accessing members of this class. The result
96 is decoded python objects (lists and dicts).
97
98 The Twitter API is documented here:
99
100 http://apiwiki.twitter.com/
101 http://groups.google.com/group/twitter-development-talk/web/api-documentation
102
103 Examples::
104
105 twitter = Twitter("hello@foo.com", "password123")
106
107 # Get the public timeline
108 twitter.statuses.public_timeline()
109
110 # Get a particular friend's timeline
111 twitter.statuses.friends_timeline(id="billybob")
112
113 # Also supported (but totally weird)
114 twitter.statuses.friends_timeline.billybob()
115
116 # Send a direct message
117 twitter.direct_messages.new(
118 user="billybob",
119 text="I think yer swell!")
120
121 Searching Twitter::
122
123 twitter_search = Twitter(domain="search.twitter.com")
124
125 # Find the latest search trends
126 twitter_search.trends()
127
128 # Search for the latest News on #gaza
129 twitter_search.search(q="#gaza")
130
131 Using the data returned::
132
133 Twitter API calls return decoded JSON. This is converted into
134 a bunch of Python lists, dicts, ints, and strings. For example,
135
136 x = twitter.statuses.public_timeline()
137
138 # The first 'tweet' in the timeline
139 x[0]
140
141 # The screen name of the user who wrote the first 'tweet'
142 x[0]['user']['screen_name']
143
144 Getting raw XML data::
145
146 If you prefer to get your Twitter data in XML format, pass
147 format="xml" to the Twitter object when you instantiate it:
148
149 twitter = Twitter(format="xml")
150
151 The output will not be parsed in any way. It will be a raw string
152 of XML.
153 """
154 def __init__(
155 self, email=None, password=None, format="json", domain="twitter.com",
156 agent=None):
157 """
158 Create a new twitter API connector using the specified
159 credentials (email and password). Format specifies the output
160 format ("json" (default) or "xml").
161 """
162 if (format not in ("json", "xml")):
163 raise TwitterError("Unknown data format '%s'" %(format))
164 TwitterCall.__init__(self, email, password, format, domain, "", agent)
165
166 __all__ = ["Twitter", "TwitterError"]