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