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

Josh Roesslein's avatar
Josh Roesslein committed
5
import urllib
6
import time
7
import re
8
9

import requests
10

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

15

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

Josh Roesslein's avatar
Josh Roesslein committed
18

Jordi Riera's avatar
Jordi Riera committed
19
def bind_api(**config):
20
21
22

    class APIMethod(object):

Jordi Riera's avatar
Jordi Riera committed
23
24
25
26
27
28
29
30
31
        api = config['api']
        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)
        use_cache = config.get('use_cache', True)
Aaron Hill's avatar
Aaron Hill committed
32
        session = requests.Session()
33

34
        def __init__(self, args, kwargs):
Jordi Riera's avatar
Jordi Riera committed
35
            api = self.api
36
37
38
39
40
            # If authentication is required and no credentials
            # are provided, throw an error.
            if self.require_auth and not api.auth:
                raise TweepError('Authentication required!')

41
42
43
44
45
46
47
48
49
            self.post_data = kwargs.pop('post_data', None)
            self.retry_count = kwargs.pop('retry_count', api.retry_count)
            self.retry_delay = kwargs.pop('retry_delay', api.retry_delay)
            self.retry_errors = kwargs.pop('retry_errors', api.retry_errors)
            self.wait_on_rate_limit = kwargs.pop('wait_on_rate_limit', api.wait_on_rate_limit)
            self.wait_on_rate_limit_notify = kwargs.pop('wait_on_rate_limit_notify', api.wait_on_rate_limit_notify)
            self.parser = kwargs.pop('parser', api.parser)
            self.session.headers = kwargs.pop('headers', {})
            self.build_parameters(args, kwargs)
50
51
52
53
54
55
56
57
58

            # 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()
59

60
61
            if self.search_api:
                self.host = api.search_host
62
            else:
63
64
                self.host = api.host

65
66
67
            # 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
68
            # See Issue https://github.com/tweepy/tweepy/issues/12
Aaron Hill's avatar
Aaron Hill committed
69
70

            self.session.headers['Host'] = self.host
71
72
73
            # Monitoring rate limits
            self._remaining_calls = None
            self._reset_time = None
74

75
        def build_parameters(self, args, kwargs):
Aaron Hill's avatar
Aaron Hill committed
76
            self.session.params = {}
77
            for idx, arg in enumerate(args):
78
79
                if arg is None:
                    continue
80
                try:
Aaron Hill's avatar
Aaron Hill committed
81
                    self.session.params[self.allowed_param[idx]] = convert_to_utf8_str(arg)
82
83
84
                except IndexError:
                    raise TweepError('Too many parameters supplied!')

85
            for k, arg in kwargs.items():
86
87
                if arg is None:
                    continue
Aaron Hill's avatar
Aaron Hill committed
88
                if k in self.session.params:
89
90
                    raise TweepError('Multiple values for parameter %s supplied!' % k)

Aaron Hill's avatar
Aaron Hill committed
91
                self.session.params[k] = convert_to_utf8_str(arg)
92
93
94
95
96

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

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

107
108
                self.path = self.path.replace(variable, value)

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

112
113
            # Build the request URL
            url = self.api_root + self.path
Joshua Roesslein's avatar
Joshua Roesslein committed
114
            full_url = 'https://' + self.host + url
115
116
117

            # Query the cache if one is available
            # and this request uses a GET method.
118
            if self.use_cache and self.api.cache and self.method == 'GET':
119
                cache_result = self.api.cache.get(url)
120
121
122
123
124
                # 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:
125
126
                            if isinstance(result, Model):
                                result._api = self.api
127
                    else:
128
129
                        if isinstance(cache_result, Model):
                            cache_result._api = self.api
Joshua Roesslein's avatar
Joshua Roesslein committed
130
                    self.api.cached_result = True
131
132
133
134
135
136
                    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:
137
138
                # handle running out of api calls
                if self.wait_on_rate_limit and self._reset_time is not None and \
139
                                self._remaining_calls is not None and self._remaining_calls < 1:
140
141
                    sleep_time = self._reset_time - int(time.time())
                    if sleep_time > 0:
142
143
                        if self.wait_on_rate_limit_notify:
                            print "Max retries reached. Sleeping for: " + str(sleep_time)
144
                        time.sleep(sleep_time + 5)  # sleep for few extra sec
145

146
147
                # Apply authentication
                if self.api.auth:
Aaron Hill's avatar
Aaron Hill committed
148
                    auth = self.api.auth.apply_auth()
149

Mike's avatar
Mike committed
150
151
                # Request compression if configured
                if self.api.compression:
Aaron Hill's avatar
Aaron Hill committed
152
                    self.session.headers['Accept-encoding'] = 'gzip'
Mike's avatar
Mike committed
153

154
155
                # Execute request
                try:
Aaron Hill's avatar
Aaron Hill committed
156
                    resp = self.session.request(self.method, full_url,
157
158
                                                data=self.post_data, timeout=self.api.timeout,
                                                auth=auth, proxies=self.api.proxy)
Aaron Hill's avatar
Aaron Hill committed
159
                except Exception, e:
160
                    raise TweepError('Failed to send request: %s' % e)
161
                rem_calls = resp.headers.get('x-rate-limit-remaining')
162
                if rem_calls is not None:
163
                    self._remaining_calls = int(rem_calls)
164
165
                elif isinstance(self._remaining_calls, int):
                    self._remaining_calls -= 1
166
                reset_time = resp.headers.get('x-rate-limit-reset')
167
                if reset_time is not None:
168
                    self._reset_time = int(reset_time)
169
170
                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
171
                    continue
172
                retry_delay = self.retry_delay
173
                # Exit request loop if non-retry error code
Aaron Hill's avatar
Aaron Hill committed
174
                if resp.status_code == 200:
175
                    break
Aaron Hill's avatar
Aaron Hill committed
176
177
178
179
                elif (resp.status_code == 429 or resp.status_code == 420) and self.wait_on_rate_limit:
                    if 'retry-after' in resp.headers:
                        retry_delay = float(resp.headers['retry-after'])
                elif self.retry_errors and resp.status_code not in self.retry_errors:
180
                    break
181

182
                # Sleep before retrying request again
183
                time.sleep(retry_delay)
184
                retries_performed += 1
Josh Roesslein's avatar
Josh Roesslein committed
185

186
187
            # If an error was returned, throw an exception
            self.api.last_response = resp
188
            if resp.status_code and not 200 <= resp.status_code < 300:
189
                try:
Aaron Hill's avatar
Aaron Hill committed
190
                    error_msg = self.parser.parse_error(resp.text)
191
                except Exception:
Aaron Hill's avatar
Aaron Hill committed
192
                    error_msg = "Twitter error response: status code = %s" % resp.status_code
193
                raise TweepError(error_msg, resp)
194
195

            # Parse the response payload
196
            result = self.parser.parse(self, resp.text)
197
198

            # Store result into cache if one is available.
199
            if self.use_cache and self.api.cache and self.method == 'GET' and result:
200
                self.api.cache.store(url, result)
201

202
            return result
Josh Roesslein's avatar
Josh Roesslein committed
203

204
205
206
    def _call(*args, **kwargs):
        method = APIMethod(args, kwargs)
        if kwargs.get('create'):
207
208
209
            return method
        else:
            return method.execute()
Josh Roesslein's avatar
Josh Roesslein committed
210

211
    # Set pagination mode
212
    if 'cursor' in APIMethod.allowed_param:
213
        _call.pagination_mode = 'cursor'
214
    elif 'max_id' in APIMethod.allowed_param and \
215
                    'since_id' in APIMethod.allowed_param:
216
        _call.pagination_mode = 'id'
217
    elif 'page' in APIMethod.allowed_param:
218
        _call.pagination_mode = 'page'
219

Josh Roesslein's avatar
Josh Roesslein committed
220
    return _call