Package restkit :: Package util :: Module sock
[hide private]
[frames] | no frames]

Source Code for Module restkit.util.sock

 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  import socket 
 7   
 8  CHUNK_SIZE = (16 * 1024) 
 9  MAX_BODY = 1024 * 112 
10   
11  try: 
12      import ssl # python 2.6 
13      have_ssl = True 
14  except ImportError: 
15      have_ssl = False 
16           
17  if not hasattr(socket, '_GLOBAL_DEFAULT_TIMEOUT'): # python < 2.6 
18      _GLOBAL_DEFAULT_TIMEOUT = object() 
19  else: 
20      _GLOBAL_DEFAULT_TIMEOUT = socket._GLOBAL_DEFAULT_TIMEOUT 
21       
22  _allowed_ssl_args = ('keyfile', 'certfile', 'server_side', 
23                      'cert_reqs', 'ssl_version', 'ca_certs',  
24                      'do_handshake_on_connect', 'suppress_ragged_eofs') 
25   
26 -def connect(address, is_ssl, timeout=_GLOBAL_DEFAULT_TIMEOUT, **ssl_args):
27 ssl_args = ssl_args or {} 28 msg = "getaddrinfo returns an empty list" 29 host, port = address 30 for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): 31 af, socktype, proto, canonname, sa = res 32 sock = None 33 try: 34 sock = socket.socket(af, socktype, proto) 35 if timeout is not _GLOBAL_DEFAULT_TIMEOUT: 36 sock.settimeout(timeout) 37 sock.connect(sa) 38 if is_ssl: 39 if not have_ssl: 40 raise ValueError("https isn't supported. On python 2.5x," 41 + " https support requires ssl module " 42 + "(http://pypi.python.org/pypi/ssl) " 43 + "to be intalled.") 44 45 for arg in ssl_args: 46 if arg not in _allowed_ssl_args: 47 raise TypeError('connect() got an unexpected keyword argument %r' % arg) 48 return ssl.wrap_socket(sock, **ssl_args) 49 return sock 50 except socket.error, msg: 51 if sock is not None: 52 sock.close() 53 raise socket.error, msg
54
55 -def close(skt):
56 if not skt or not hasattr(skt, "close"): return 57 try: 58 skt.close() 59 except socket.error: 60 pass
61
62 -def send_chunk(sock, data):
63 chunk = "".join(("%X\r\n" % len(data), data, "\r\n")) 64 sock.sendall(chunk)
65
66 -def send(sock, data, chunked=False):
67 if chunked: 68 return send_chunk(sock, data) 69 sock.sendall(data)
70
71 -def send_nonblock(sock, data, chunked=False):
72 timeout = sock.gettimeout() 73 if timeout != 0.0: 74 try: 75 sock.setblocking(0) 76 return send(sock, data, chunked) 77 finally: 78 sock.setblocking(1) 79 else: 80 return send(sock, data, chunked)
81
82 -def sendlines(sock, lines, chunked=False):
83 for line in list(lines): 84 send(sock, line, chunked)
85
86 -def sendfile(sock, data, chunked=False):
87 if hasattr(data, 'seek'): 88 data.seek(0) 89 90 while True: 91 binarydata = data.read(CHUNK_SIZE) 92 if binarydata == '': break 93 send(sock, binarydata, chunked)
94