binder.py 7.69 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
43
44
45
46
47
48
49
50
51
52
53

        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)
            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()
54

55
            if api.secure:
56
                self.scheme = 'https://'
57
            else:
58
59
60
61
                self.scheme = 'http://'

            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
69
70
            self.headers['Host'] = self.host

71
72
73
        def build_parameters(self, args, kargs):
            self.parameters = {}
            for idx, arg in enumerate(args):
74
75
                if arg is None:
                    continue
76
77

                try:
78
                    self.parameters[self.allowed_param[idx]] = convert_to_utf8_str(arg)
79
80
81
82
83
84
85
86
87
                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)

88
                self.parameters[k] = convert_to_utf8_str(arg)
89
90
91
92
93

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

94
95
96
97
98
99
100
101
102
                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]
103

104
105
                self.path = self.path.replace(variable, value)

106
107
108
109
110
111
112
113
        def execute(self):
            # 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.
114
            if self.use_cache and self.api.cache and self.method == 'GET':
115
                cache_result = self.api.cache.get(url)
116
117
118
119
120
                # 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:
121
122
                            if isinstance(result, Model):
                                result._api = self.api
123
                    else:
124
125
                        if isinstance(cache_result, Model):
                            cache_result._api = self.api
126
127
128
129
130
131
132
133
                    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:
                # Open connection
                if self.api.secure:
Joshua Roesslein's avatar
Joshua Roesslein committed
134
                    conn = httplib.HTTPSConnection(self.host, timeout=self.api.timeout)
135
                else:
Joshua Roesslein's avatar
Joshua Roesslein committed
136
                    conn = httplib.HTTPConnection(self.host, timeout=self.api.timeout)
137
138
139
140
141
142
143
144

                # 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
145
146
147
148
                # Request compression if configured
                if self.api.compression:
                    self.headers['Accept-encoding'] = 'gzip'

149
150
151
152
153
                # Execute request
                try:
                    conn.request(self.method, url, headers=self.headers, body=self.post_data)
                    resp = conn.getresponse()
                except Exception, e:
154
                    raise TweepError('Failed to send request: %s' % e)
155
156
157
158
159
160

                # Exit request loop if non-retry error code
                if self.retry_errors:
                    if resp.status not in self.retry_errors: break
                else:
                    if resp.status == 200: break
161

162
163
164
                # Sleep before retrying request again
                time.sleep(self.retry_delay)
                retries_performed += 1
Josh Roesslein's avatar
Josh Roesslein committed
165

166
167
            # If an error was returned, throw an exception
            self.api.last_response = resp
168
            if resp.status and not 200 <= resp.status < 300:
169
                try:
Ivo Wetzel's avatar
Ivo Wetzel committed
170
                    error_msg = self.api.parser.parse_error(resp.read())
171
172
                except Exception:
                    error_msg = "Twitter error response: status code = %s" % resp.status
173
                raise TweepError(error_msg, resp)
174
175

            # Parse the response payload
Mike's avatar
Mike committed
176
177
178
179
180
181
182
183
            body = resp.read()
            if resp.getheader('Content-Encoding', '') == 'gzip':
                try:
                    zipper = gzip.GzipFile(fileobj=StringIO(body))
                    body = zipper.read()
                except Exception, e:
                    raise TweepError('Failed to decompress data: %s' % e)
            result = self.api.parser.parse(self, body)
184
185

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

187
            # Store result into cache if one is available.
188
            if self.use_cache and self.api.cache and self.method == 'GET' and result:
189
                self.api.cache.store(url, result)
190

191
            return result
Josh Roesslein's avatar
Josh Roesslein committed
192
193


194
195
196
197
    def _call(api, *args, **kargs):

        method = APIMethod(api, args, kargs)
        return method.execute()
Josh Roesslein's avatar
Josh Roesslein committed
198

199
200

    # Set pagination mode
201
    if 'cursor' in APIMethod.allowed_param:
202
        _call.pagination_mode = 'cursor'
203
204
205
    elif 'max_id' in APIMethod.allowed_param and \
         'since_id' in APIMethod.allowed_param:
        _call.pagination_mode = 'id'
206
    elif 'page' in APIMethod.allowed_param:
207
        _call.pagination_mode = 'page'
208

Josh Roesslein's avatar
Josh Roesslein committed
209
210
    return _call