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

Source Code for Module restkit.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 array 
 7  import socket 
 8   
 9  CHUNK_SIZE = (16 * 1024) 
10  MAX_BODY = 1024 * (80 + 32) 
11   
12  try: 
13      import ssl # python 2.6 
14      _ssl_wrap_socket = ssl.wrap_socket 
15  except ImportError: 
16 - def _ssl_wrap_socket(sock, key_file, cert_file):
17 ssl_sock = socket.ssl(sock, key_file, cert_file) 18 return ssl_sock
19 20 if not hasattr(socket, '_GLOBAL_DEFAULT_TIMEOUT'): # python < 2.6 21 _GLOBAL_DEFAULT_TIMEOUT = object() 22 else: 23 _GLOBAL_DEFAULT_TIMEOUT = socket._GLOBAL_DEFAULT_TIMEOUT 24
25 -def connect(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, ssl=False, 26 key_file=None, cert_file=None):
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: 38 sock = _ssl_wrap_socket(sock, key_file, cert_file) 39 return sock 40 except socket.error, msg: 41 if sock is not None: 42 sock.close() 43 raise socket.error, msg
44 45
46 -def recv(sock, length, buf=None):
47 tmp_buf = array.array("c", '\0' * length) 48 l = sock.recv_into(tmp_buf, length) 49 if not buf: 50 return tmp_buf[:l] 51 52 return buf + tmp_buf[:l]
53
54 -def close(sock):
55 try: 56 sock.close() 57 except socket.error: 58 pass
59
60 -def send_chunk(sock, data):
61 chunk = "".join(("%X\r\n" % len(data), data, "\r\n")) 62 sock.sendall(chunk)
63
64 -def send(sock, data, chunked=False):
65 if chunked: 66 return send_chunk(sock, data) 67 sock.sendall(data)
68
69 -def send_nonblock(sock, data, chunked=False):
70 timeout = sock.gettimeout() 71 if timeout != 0.0: 72 try: 73 sock.setblocking(0) 74 return send(sock, data, chunked) 75 finally: 76 sock.setblocking(1) 77 else: 78 return send(sock, data, chunked)
79
80 -def sendlines(sock, lines, chunked=False):
81 for line in list(lines): 82 send(sock, line, chunked)
83
84 -def sendfile(sock, data, chunked=False):
85 if hasattr(data, 'seek'): 86 data.seek(0) 87 88 while True: 89 binarydata = data.read(CHUNK_SIZE) 90 if binarydata == '': break 91 send(sock, binarydata, chunked)
92