Advertisement
Fhernd

soporte_gestion_contexto.py

Dec 5th, 2018
1,866
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. from socket import socket, AF_INET, SOCK_STREAM
  2. from functools import partial
  3.  
  4. class ConexionDiferida:
  5.     def __init__(self, direccion, familia=AF_INET, tipo=SOCK_STREAM):
  6.         self.direccion = direccion
  7.         self.familia = AF_INET
  8.         self.tipo = SOCK_STREAM
  9.         self.sock = None
  10.  
  11.     def __enter__(self):
  12.         if self.sock is not None:
  13.             raise Runtimeerror('La conexión ya se ha realizado')
  14.  
  15.         self.sock = socket(self.familia, self.tipo)
  16.         self.sock.connect(self.direccion)
  17.  
  18.         return self.sock
  19.  
  20.     def __exit__(self, exc_type, exc_val, exc_tb):
  21.         self.sock.close()
  22.         self.sock = None
  23.  
  24.  
  25. if __name__ == '__main__':
  26.     conexion = ConexionDiferida(('www.python.org', 80))
  27.  
  28.     with conexion as s:
  29.         # conexion.__enter__() se ejecuta: la conexión se abre
  30.  
  31.         s.send(b'GET /index.html HTTP/1.0\r\n')
  32.         s.send(b'Host: www.python.org\r\n')
  33.         s.send(b'\r\n')
  34.  
  35.         respuesta = b''.join(iter(partial(s.recv, 8192), b''))
  36.  
  37.         # conexion.__exit__() se ejecuta: la conexión se cierra
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement