binder.py 1.85 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

8
from parsers import parse_error
9
from error import TweepError
10

Josh Roesslein's avatar
Josh Roesslein committed
11
def bind_api(path, parser, allowed_param=None, method='GET', require_auth=False, host=None):
12

13
14
15
16
17
18
19
20
21
22
23
  def _call(api, *args, **kargs):
    # If require auth, throw exception if credentials not provided
    if require_auth and not api._b64up:
      raise TweepError('Authentication required!')

    # Filter out unallowed parameters
    if allowed_param:
      parameters = dict((k,v) for k,v in kargs.items() if k in allowed_param)
    else:
      parameters = None

24
25
26
27
28
29
30
31
32
33
34
35
36
37
    # Build url with parameters
    if parameters:
      url = '%s?%s' % (path, urllib.urlencode(parameters))
    else:
      url = path

    # Check cache if caching enabled and method is GET
    if api.cache and method == 'GET':
      cache_result = api.cache.get(url)
      if cache_result:
        # if cache result found and not expired, return it
        print 'hit!'
        return cache_result

38
    # Open connection
Josh Roesslein's avatar
Josh Roesslein committed
39
40
41
42
    if host:
      _host = host
    else:
      _host = api.host
43
    if api.secure:
Josh Roesslein's avatar
Josh Roesslein committed
44
      conn = httplib.HTTPSConnection(_host)
45
    else:
Josh Roesslein's avatar
Josh Roesslein committed
46
      conn = httplib.HTTPConnection(_host)
47
48
49
50
51

    # Assemble headers
    headers = {
      'User-Agent': 'tweepy'
    }
52
53
    if api._b64up:
      headers['Authorization'] = 'Basic %s' % api._b64up
54
55
56
57
58
59
60
61
62
63
64
65

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

    # Get response
    resp = conn.getresponse()

    # If an error was returned, throw an exception
    if resp.status != 200:
      raise TweepError(parse_error(resp.read()))

    # Pass returned body into parser and return parser output
66
    out =  parser(resp.read(), api)
67

68
69
70
71
    # store result in cache
    if api.cache and method == 'GET':
      api.cache.store(url, out)

72
73
74
    # close connection and return data
    conn.close()
    return out
75

76
  return _call