binder.py 9.66 KB
Newer Older
1
# Tweepy
2
3
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
4

5
import httplib
Josh Roesslein's avatar
Josh Roesslein committed
6
import urllib
7
import time
8
import re
Mike's avatar
Mike committed
9
10
from StringIO import StringIO
import gzip
11

Josh Roesslein's avatar
Josh Roesslein committed
12
from tweepy.error import TweepError
13
from tweepy.utils import convert_to_utf8_str
14
from tweepy.models import Model
15

16
17
re_path_template = re.compile('{\w+}')

Josh Roesslein's avatar
Josh Roesslein committed
18

19
20
21
22
23
24
25
26
27
28
29
def bind_api(**config):

    class APIMethod(object):

        path = config['path']
        payload_type = config.get('payload_type', None)
        payload_list = config.get('payload_list', False)
        allowed_param = config.get('allowed_param', [])
        method = config.get('method', 'GET')
        require_auth = config.get('require_auth', False)
        search_api = config.get('search_api', False)
30
        use_cache = config.get('use_cache', True)
31
32
33
34
35
36
37
38
39
40
41
42

        def __init__(self, api, args, kargs):
            # If authentication is required and no credentials
            # are provided, throw an error.
            if self.require_auth and not api.auth:
                raise TweepError('Authentication required!')

            self.api = api
            self.post_data = kargs.pop('post_data', None)
            self.retry_count = kargs.pop('retry_count', api.retry_count)
            self.retry_delay = kargs.pop('retry_delay', api.retry_delay)
            self.retry_errors = kargs.pop('retry_errors', api.retry_errors)
43
            self.wait_on_rate_limit = kargs.pop('wait_on_rate_limit', api.wait_on_rate_limit)
Aaron Hill's avatar
Aaron Hill committed
44
            self.wait_on_rate_limit_notify = kargs.pop('wait_on_rate_limit_notify', api.wait_on_rate_limit_notify)
45
            self.parser = kargs.pop('parser', api.parser)
46
47
48
49
50
51
52
53
54
55
56
            self.headers = kargs.pop('headers', {})
            self.build_parameters(args, kargs)

            # Pick correct URL root to use
            if self.search_api:
                self.api_root = api.search_root
            else:
                self.api_root = api.api_root

            # Perform any path variable substitution
            self.build_path()
57

58
            if api.secure:
59
                self.scheme = 'https://'
60
            else:
61
62
63
64
                self.scheme = 'http://'

            if self.search_api:
                self.host = api.search_host
65
            else:
66
67
                self.host = api.host

68
69
70
            # Manually set Host header to fix an issue in python 2.5
            # or older where Host is set including the 443 port.
            # This causes Twitter to issue 301 redirect.
Pablo Castellano's avatar
Pablo Castellano committed
71
            # See Issue https://github.com/tweepy/tweepy/issues/12
72
            self.headers['Host'] = self.host
73
74
75
            # Monitoring rate limits
            self._remaining_calls = None
            self._reset_time = None
76

77
78
79
        def build_parameters(self, args, kargs):
            self.parameters = {}
            for idx, arg in enumerate(args):
80
81
                if arg is None:
                    continue
82
                try:
83
                    self.parameters[self.allowed_param[idx]] = convert_to_utf8_str(arg)
84
85
86
87
88
89
90
91
92
                except IndexError:
                    raise TweepError('Too many parameters supplied!')

            for k, arg in kargs.items():
                if arg is None:
                    continue
                if k in self.parameters:
                    raise TweepError('Multiple values for parameter %s supplied!' % k)

93
                self.parameters[k] = convert_to_utf8_str(arg)
94
95
96
97
98

        def build_path(self):
            for variable in re_path_template.findall(self.path):
                name = variable.strip('{}')

99
100
101
102
103
104
105
106
107
                if name == 'user' and 'user' not in self.parameters and self.api.auth:
                    # No 'user' parameter provided, fetch it from Auth instead.
                    value = self.api.auth.get_username()
                else:
                    try:
                        value = urllib.quote(self.parameters[name])
                    except KeyError:
                        raise TweepError('No parameter value found for path variable: %s' % name)
                    del self.parameters[name]
108

109
110
                self.path = self.path.replace(variable, value)

111
        def execute(self):
Joshua Roesslein's avatar
Joshua Roesslein committed
112
113
            self.api.cached_result = False

114
115
116
117
118
119
120
            # Build the request URL
            url = self.api_root + self.path
            if len(self.parameters):
                url = '%s?%s' % (url, urllib.urlencode(self.parameters))

            # Query the cache if one is available
            # and this request uses a GET method.
121
            if self.use_cache and self.api.cache and self.method == 'GET':
122
                cache_result = self.api.cache.get(url)
123
124
125
126
127
                # if cache result found and not expired, return it
                if cache_result:
                    # must restore api reference
                    if isinstance(cache_result, list):
                        for result in cache_result:
128
129
                            if isinstance(result, Model):
                                result._api = self.api
130
                    else:
131
132
                        if isinstance(cache_result, Model):
                            cache_result._api = self.api
Joshua Roesslein's avatar
Joshua Roesslein committed
133
                    self.api.cached_result = True
134
135
136
137
138
139
                    return cache_result

            # Continue attempting request until successful
            # or maximum number of retries is reached.
            retries_performed = 0
            while retries_performed < self.retry_count + 1:
140
141
142
143
144
                # handle running out of api calls
                if self.wait_on_rate_limit and self._reset_time is not None and \
                   self._remaining_calls is not None and self._remaining_calls < 1:
                    sleep_time = self._reset_time - int(time.time())
                    if sleep_time > 0:
145
146
147
148
                        if self.wait_on_rate_limit_notify:
                            print "Max retries reached. Sleeping for: " + str(sleep_time)
                        time.sleep(sleep_time + 5) # sleep for few extra sec

149
150
                # Open connection
                if self.api.secure:
Joshua Roesslein's avatar
Joshua Roesslein committed
151
                    conn = httplib.HTTPSConnection(self.host, timeout=self.api.timeout)
152
                else:
Joshua Roesslein's avatar
Joshua Roesslein committed
153
                    conn = httplib.HTTPConnection(self.host, timeout=self.api.timeout)
154
155
156
157
158
159
160
161

                # Apply authentication
                if self.api.auth:
                    self.api.auth.apply_auth(
                            self.scheme + self.host + url,
                            self.method, self.headers, self.parameters
                    )

Mike's avatar
Mike committed
162
163
164
165
                # Request compression if configured
                if self.api.compression:
                    self.headers['Accept-encoding'] = 'gzip'

166
167
168
169
                # Execute request
                try:
                    conn.request(self.method, url, headers=self.headers, body=self.post_data)
                    resp = conn.getresponse()
170
                except Exception as e:
171
                    raise TweepError('Failed to send request: %s' % e)
172
173
                rem_calls = resp.getheader('x-rate-limit-remaining')
                if rem_calls is not None:
174
                    self._remaining_calls = int(rem_calls)
175
176
177
178
                elif isinstance(self._remaining_calls, int):
                    self._remaining_calls -= 1
                reset_time = resp.getheader('x-rate-limit-reset')
                if reset_time is not None:
179
                    self._reset_time = int(reset_time)
180
                if self.wait_on_rate_limit and self._remaining_calls == 0 and (resp.status == 429 or resp.status == 420): # if ran out of calls before waiting switching retry last call
181
                    continue
182
                retry_delay = self.retry_delay
183
                # Exit request loop if non-retry error code
184
185
186
187
188
189
                if resp.status == 200:
                    break
                elif (resp.status == 429 or resp.status == 420) and self.wait_on_rate_limit:
                    if 'retry-after' in resp.msg:
                        retry_delay = float(resp.msg['retry-after'])
                elif self.retry_errors and resp.status not in self.retry_errors:
190
                    break
191

192
                # Sleep before retrying request again
193
                time.sleep(retry_delay)
194
                retries_performed += 1
Josh Roesslein's avatar
Josh Roesslein committed
195

196
197
            # If an error was returned, throw an exception
            self.api.last_response = resp
198
            if resp.status and not 200 <= resp.status < 300:
199
                try:
200
                    error_msg = self.parser.parse_error(resp.read())
201
202
                except Exception:
                    error_msg = "Twitter error response: status code = %s" % resp.status
203
                raise TweepError(error_msg, resp)
204
205

            # Parse the response payload
Mike's avatar
Mike committed
206
207
208
209
210
            body = resp.read()
            if resp.getheader('Content-Encoding', '') == 'gzip':
                try:
                    zipper = gzip.GzipFile(fileobj=StringIO(body))
                    body = zipper.read()
211
                except Exception as e:
Mike's avatar
Mike committed
212
                    raise TweepError('Failed to decompress data: %s' % e)
213
214
            
            result = self.parser.parse(self, body)
215
216

            conn.close()
Josh Roesslein's avatar
Josh Roesslein committed
217

218
            # Store result into cache if one is available.
219
            if self.use_cache and self.api.cache and self.method == 'GET' and result:
220
                self.api.cache.store(url, result)
221

222
            return result
Josh Roesslein's avatar
Josh Roesslein committed
223

224
    def _call(api, create=False, *args, **kargs):
225
226

        method = APIMethod(api, args, kargs)
227
228
229
230
        if create:
            return method
        else:
            return method.execute()
Josh Roesslein's avatar
Josh Roesslein committed
231

232
233

    # Set pagination mode
234
    if 'cursor' in APIMethod.allowed_param:
235
        _call.pagination_mode = 'cursor'
236
237
238
    elif 'max_id' in APIMethod.allowed_param and \
         'since_id' in APIMethod.allowed_param:
        _call.pagination_mode = 'id'
239
    elif 'page' in APIMethod.allowed_param:
240
        _call.pagination_mode = 'page'
241

Josh Roesslein's avatar
Josh Roesslein committed
242
    return _call