http.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import ipaddress
  2. import sys
  3. from .imports import lazy_import
  4. from .version import version as websockets_version
  5. # For backwards compatibility:
  6. lazy_import(
  7. globals(),
  8. # Headers and MultipleValuesError used to be defined in this module.
  9. aliases={
  10. "Headers": ".datastructures",
  11. "MultipleValuesError": ".datastructures",
  12. },
  13. deprecated_aliases={
  14. "read_request": ".legacy.http",
  15. "read_response": ".legacy.http",
  16. },
  17. )
  18. __all__ = ["USER_AGENT", "build_host"]
  19. PYTHON_VERSION = "{}.{}".format(*sys.version_info)
  20. USER_AGENT = f"Python/{PYTHON_VERSION} websockets/{websockets_version}"
  21. def build_host(host: str, port: int, secure: bool) -> str:
  22. """
  23. Build a ``Host`` header.
  24. """
  25. # https://tools.ietf.org/html/rfc3986#section-3.2.2
  26. # IPv6 addresses must be enclosed in brackets.
  27. try:
  28. address = ipaddress.ip_address(host)
  29. except ValueError:
  30. # host is a hostname
  31. pass
  32. else:
  33. # host is an IP address
  34. if address.version == 6:
  35. host = f"[{host}]"
  36. if port != (443 if secure else 80):
  37. host = f"{host}:{port}"
  38. return host