Package restkit :: Module filters
[hide private]
[frames] | no frames]

Source Code for Module restkit.filters

  1  # -*- coding: utf-8 - 
  2  # 
  3  # This file is part of restkit released under the MIT license.  
  4  # See the NOTICE for more information. 
  5   
  6  """ 
  7  filters - Http filters 
  8   
  9  Http filters are object used before sending the request to the server 
 10  and after. The `HttpClient` instance is passed as argument. 
 11   
 12  An object with a method `on_request` is called just before the request.  
 13  An object with a method `on_response` is called after fetching response headers. 
 14   
 15  ex:: 
 16   
 17      class MyFilter(object): 
 18           
 19          def on_request(self, http_client): 
 20              "do something with/to http_client instance" 
 21   
 22          def on_response(self, http_client): 
 23              "do something on http_client and get response infos" 
 24               
 25               
 26  """ 
 27   
 28  import base64 
 29  import os 
 30  import urlparse 
 31   
 32   
 33  from restkit.errors import InvalidUrl 
 34  from restkit.parser import Parser 
 35  from restkit import sock 
 36  from restkit import util 
 37  from restkit import __version__ 
 38   
39 -class BasicAuth(object):
40 """ Simple filter to manage basic authentification""" 41
42 - def __init__(self, username, password):
43 self.credentials = (username, password)
44
45 - def on_request(self, req):
46 encode = base64.encodestring("%s:%s" % self.credentials)[:-1] 47 req.headers.append(('Authorization', 'Basic %s' % encode))
48
49 -class ProxyError(Exception):
50 pass
51
52 -class SimpleProxy(object):
53 """ Simple proxy filter. 54 This filter find proxy from environment and if it exists it 55 connect to the proxy and modify connection headers. 56 """ 57
58 - def _host_port(self, proxy_uri):
59 proxy_host = proxy_uri.netloc 60 i = proxy_host.rfind(':') 61 j = proxy_host.rfind(']') 62 if i > j: 63 try: 64 proxy_port = int(proxy_host[i+1:]) 65 except ValueError: 66 raise InvalidUrl("nonnumeric port: '%s'" % proxy_host[i+1:]) 67 proxy_host = proxy_host[:i] 68 else: 69 proxy_port = 80 70 71 if proxy_host and proxy_host[0] == '[' and proxy_host[-1] == ']': 72 proxy_host = proxy_host[1:-1] 73 74 return proxy_host, proxy_port
75
76 - def on_request(self, req):
77 proxy_auth = _get_proxy_auth() 78 if req.uri.scheme == "https": 79 proxy = os.environ.get('https_proxy') 80 if proxy: 81 if proxy_auth: 82 proxy_auth = 'Proxy-authorization: %s' % proxy_auth 83 proxy_connect = 'CONNECT %s HTTP/1.0\r\n' % (req.uri.netloc) 84 user_agent = "User-Agent: restkit/%s\r\n" % __version__ 85 proxy_pieces = '%s%s%s\r\n' % (proxy_connect, proxy_auth, 86 user_agent) 87 proxy_uri = urlparse.urlparse(proxy) 88 proxy_host, proxy_port = self._host_port(proxy_uri) 89 # Connect to the proxy server, 90 # very simple recv and error checking 91 92 p_sock = sock.connect((proxy_host, int(proxy_port)) ) 93 sock.send(p_sock, proxy_pieces) 94 95 # wait header 96 p = Parser.parse_response() 97 headers = [] 98 buf = "" 99 buf = sock.recv(p_sock, util.CHUNK_SIZE) 100 i = self.parser.filter_headers(headers, buf) 101 if i == -1 and buf: 102 while True: 103 data = sock.recv(p_sock, util.CHUNK_SIZE) 104 if not data: break 105 buf += data 106 i = self.parser.filter_headers(headers, buf) 107 if i != -1: break 108 109 if p.status_int != 200: 110 raise ProxyError('Error status=%s' % p.status) 111 112 sock._ssl_wrap_socket(p_sock, None, None) 113 114 # update socket 115 req.socket = p_sock 116 req.host = proxy_host 117 else: 118 proxy = os.environ.get('http_proxy') 119 if proxy: 120 proxy_uri = urlparse.urlparse(proxy) 121 proxy_host, proxy_port = self._host_port(proxy_uri) 122 if proxy_auth: 123 headers['Proxy-Authorization'] = proxy_auth.strip() 124 req.headers.append(('Proxy-Authorization', 125 proxy_auth.strip())) 126 req.host = proxy_host 127 req.port = proxy_port
128 129
130 -def _get_proxy_auth():
131 proxy_username = os.environ.get('proxy-username') 132 if not proxy_username: 133 proxy_username = os.environ.get('proxy_username') 134 proxy_password = os.environ.get('proxy-password') 135 if not proxy_password: 136 proxy_password = os.environ.get('proxy_password') 137 if proxy_username: 138 user_auth = base64.encodestring('%s:%s' % (proxy_username, 139 proxy_password)) 140 return 'Basic %s\r\n' % (user_auth.strip()) 141 else: 142 return ''
143