sparty.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. #!/usr/bin/env python3
  2. # vim: tabstop=4 shiftwidth=4 expandtab
  3. import socket
  4. import urllib.parse
  5. class Response():
  6. def __init__(self, socket: socket.socket) -> "Response":
  7. self._socket = socket
  8. self._filehandle = self._socket.makefile(mode = "rb")
  9. try:
  10. self.responsecode, self.meta = self._filehandle.readline(1027).split(maxsplit=1)
  11. self.responsecode = int(self.responsecode)
  12. self.meta = self.meta.strip().decode("ASCII")
  13. except:
  14. self.discard()
  15. raise RuntimeError("Received malformed header from spartan server")
  16. def read(self, bufsize: int = 4096) -> "bytes":
  17. return self._filehandle.read(bufsize)
  18. def discard(self) -> None:
  19. self._filehandle.close()
  20. self._socket.close()
  21. def request(url: str = "", message: bytes = "") -> "Response":
  22. url = f"spartan://{url}" if not url.startswith("spartan://") else url
  23. parsed = urllib.parse.urlparse(url)
  24. data = str.encode(parsed.query) or message
  25. sock = socket.create_connection((parsed.hostname, parsed.port or 300))
  26. sock.sendall(f"{parsed.hostname} {parsed.path or '/'} {len(data)}\r\n".encode("ASCII"))
  27. if data:
  28. sock.sendall(data)
  29. return Response(sock)