binder.py 1.5 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
    # Open connection
Josh Roesslein's avatar
Josh Roesslein committed
25
26
27
28
    if host:
      _host = host
    else:
      _host = api.host
29
    if api.secure:
Josh Roesslein's avatar
Josh Roesslein committed
30
      conn = httplib.HTTPSConnection(_host)
31
    else:
Josh Roesslein's avatar
Josh Roesslein committed
32
      conn = httplib.HTTPConnection(_host)
33

34
35
36
37
38
39
    # Build url with parameters
    if parameters:
      url = '%s?%s' % (path, urllib.urlencode(parameters))
    else:
      url = path

40
41
42
43
    # Assemble headers
    headers = {
      'User-Agent': 'tweepy'
    }
44
45
    if api._b64up:
      headers['Authorization'] = 'Basic %s' % api._b64up
46
47
48
49
50
51
52
53
54
55
56
57

    # 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
58
    out =  parser(resp.read(), api)
59
60
61
62

    # close connection and return data
    conn.close()
    return out
63

64
  return _call