binder.py 5.42 KB
Newer Older
1
2
3
4
# Tweepy
# Copyright 2009 Joshua Roesslein
# See LICENSE

5
import httplib
Josh Roesslein's avatar
Josh Roesslein committed
6
import urllib
7

Josh Roesslein's avatar
Josh Roesslein committed
8
9
from . parsers import parse_error
from . error import TweepError
10

11
12
13
14
15
16
17
18
19
20
21
try:
    import json #Python >= 2.6
except ImportError:
    try:
        import simplejson as json #Python < 2.6
    except ImportError:
        try:
            from django.utils import simplejson as json #Google App Engine
        except ImportError:
            raise ImportError, "Can't load a json library"

Josh Roesslein's avatar
Josh Roesslein committed
22

23
24
def bind_api(path, parser, allowed_param=None, method='GET', require_auth=False,
              timeout=None, host=None):
25

Josh Roesslein's avatar
Josh Roesslein committed
26
27
28
29
30
    def _call(api, *args, **kargs):
        # If require auth, throw exception if credentials not provided
        if require_auth and not api.auth_handler:
            raise TweepError('Authentication required!')

31
32
33
34
35
        # Log some useful infomation
        api.logger.debug('Starting request...')
        api.logger.debug('  path: %s' % path)
        api.logger.debug('  method: %s' % method)

Josh Roesslein's avatar
Josh Roesslein committed
36
37
38
39
        # check for post_data parameter
        if 'post_data' in kargs:
            post_data = kargs['post_data']
            del kargs['post_data']
40
            api.logger.debug('  post data: %s' % post_data)
Josh Roesslein's avatar
Josh Roesslein committed
41
42
43
44
45
46
47
48
49
        else:
            post_data = None

        # check for headers
        if 'headers' in kargs:
            headers = dict(kargs['headers'])
            del kargs['headers']
        else:
            headers = {}
50
        api.logger.debug('  headers: %s' % headers)
Josh Roesslein's avatar
Josh Roesslein committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

        # build parameter dict
        if allowed_param:
            parameters = {}
            for idx, arg in enumerate(args):
                try:
                    parameters[allowed_param[idx]] = arg
                except IndexError:
                    raise TweepError('Too many parameters supplied!')
            for k, arg in kargs.items():
                if arg is None:
                    continue
                if k in parameters:
                    raise TweepError('Multiple values for parameter %s supplied!' % k)
                if k not in allowed_param:
                    raise TweepError('Invalid parameter %s supplied!' % k)
                parameters[k] = arg
68
        else:
Josh Roesslein's avatar
Josh Roesslein committed
69
70
71
            if len(args) > 0 or len(kargs) > 0:
                raise TweepError('This method takes no parameters!')
            parameters = None
72
        api.logger.debug('  parameters: %s' % parameters)
Josh Roesslein's avatar
Josh Roesslein committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

        # Build url with parameters
        if parameters:
            url = '%s?%s' % (api.api_root + path, urllib.urlencode(parameters))
        else:
            url = api.api_root + path

        # get scheme and host
        if api.secure:
            scheme = 'https://'
        else:
            scheme = 'http://'
        _host = host or api.host

        # Apply authentication
        if api.auth_handler:
89
90
91
92
            api.auth_handler.apply_auth(
                    scheme + _host + url,
                    method, headers, parameters
            )
Josh Roesslein's avatar
Josh Roesslein committed
93
94
95
96
97
98
99
100
101
102
103
104

        # Check cache if caching enabled and method is GET
        if api.cache and method == 'GET':
            cache_result = api.cache.get(url, timeout)
            # 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:
                        result._api = api
                else:
                    cache_result._api = api
105
                api.logger.debug("Cache hit!")
Josh Roesslein's avatar
Josh Roesslein committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
                return cache_result

        # Open connection
        # FIXME: add timeout
        if api.secure:
            conn = httplib.HTTPSConnection(_host)
        else:
            conn = httplib.HTTPConnection(_host)

        # Build request
        conn.request(method, url, headers=headers, body=post_data)

        # Get response
        resp = conn.getresponse()
120
        api.last_response = resp
121
122
123
        api.logger.debug('Received response...')
        api.logger.debug('  headers: %s' % resp.getheaders())
        api.logger.debug('  status code: %s' % resp.status)
Josh Roesslein's avatar
Josh Roesslein committed
124
125
126
127
128
129
130

        # If an error was returned, throw an exception
        if resp.status != 200:
            try:
                error_msg = parse_error(resp.read())
            except Exception:
                error_msg = "Twitter error response: status code = %s" % resp.status
131
            api.logger.error('  Error: %s' % error_msg)
Josh Roesslein's avatar
Josh Roesslein committed
132
133
            raise TweepError(error_msg)

134
135
136
137
138
139
140
        # Parse json respone body
        try:
            jobject = json.loads(resp.read())
        except Exception:
            raise TweepError("Failed to parse json response text")

        # Pass json object into parser
141
        try:
142
            out = parser(jobject, api)
143
        except Exception:
144
            raise TweepError("Failed to parse json object")
145

Josh Roesslein's avatar
Josh Roesslein committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
        conn.close()

        # validate result
        if api.validate:
            # list of results
            if isinstance(out, list) and len(out) > 0:
                if hasattr(out[0], 'validate'):
                    for result in out:
                        result.validate()
            # single result
            else:
                if hasattr(out, 'validate'):
                    out.validate()

        # store result in cache
        if api.cache and method == 'GET':
            api.cache.store(url, out)
163
164
165
            api.logger.debug("  caching result")

        api.logger.debug('request done.')
Josh Roesslein's avatar
Josh Roesslein committed
166
167
168

        return out

169
170
171
    # Expose extra data in callable object
    _call.allowed_param = allowed_param

Josh Roesslein's avatar
Josh Roesslein committed
172
173
    return _call