Build a ``Host`` header.
(
host: str,
port: int,
secure: bool,
*,
always_include_port: bool = False,
)
| 37 | |
| 38 | |
| 39 | def build_host( |
| 40 | host: str, |
| 41 | port: int, |
| 42 | secure: bool, |
| 43 | *, |
| 44 | always_include_port: bool = False, |
| 45 | ) -> str: |
| 46 | """ |
| 47 | Build a ``Host`` header. |
| 48 | |
| 49 | """ |
| 50 | # https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2 |
| 51 | # IPv6 addresses must be enclosed in brackets. |
| 52 | try: |
| 53 | address = ipaddress.ip_address(host) |
| 54 | except ValueError: |
| 55 | # host is a hostname |
| 56 | pass |
| 57 | else: |
| 58 | # host is an IP address |
| 59 | if address.version == 6: |
| 60 | host = f"[{host}]" |
| 61 | |
| 62 | if always_include_port or port != (443 if secure else 80): |
| 63 | host = f"{host}:{port}" |
| 64 | |
| 65 | return host |
| 66 | |
| 67 | |
| 68 | # To avoid a dependency on a parsing library, we implement manually the ABNF |
no outgoing calls
searching dependent graphs…