Skip to content
Myr

_main.py

This file

Path

httpx/_main.py

506 lines · 15.4 KiB · Python

Last changed by

Typing: enable warn_return_any (#2477)Martijn Pietersbefore adoption2d37321

History of this file

Take it

Tidy up the formatting of HTTP/2 requests (#1860)Tom Christiebefore adoptione1abaf1

line 1why, one step back
1import functools

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 2–6why, one step back
2import json
3import sys4import typing56import click

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

line 7why, one step back
7import httpcore

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 8–10why, one step back
8import pygments.lexers
9import pygments.util10import rich.console

Fix console markup escaping issue (#1866)Will McGuganbefore adoption2814fd3

line 11why, one step back
11import rich.markup

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 12–13why, one step back
12import rich.progress
13import rich.syntax

Fix console markup escaping issue (#1866)Will McGuganbefore adoption2814fd3

line 14why, one step back
14import rich.table

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 15–17why, one step back
15
16from ._client import Client17from ._exceptions import RequestError

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

lines 18–19why, one step back
18from ._models import Response
19from ._status_codes import codes

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 20–67why, one step back
20
2122def print_help() -> None:23 console = rich.console.Console()2425 console.print("[bold]HTTPX :butterfly:", justify="center")26 console.print()27 console.print("A next generation HTTP client.", justify="center")28 console.print()29 console.print(30 "Usage: [bold]httpx[/bold] [cyan]<URL> [OPTIONS][/cyan] ", justify="left"31 )32 console.print()3334 table = rich.table.Table.grid(padding=1, pad_edge=True)35 table.add_column("Parameter", no_wrap=True, justify="left", style="bold")36 table.add_column("Description")37 table.add_row(38 "-m, --method [cyan]METHOD",39 "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.\n"40 "[Default: GET, or POST if a request body is included]",41 )42 table.add_row(43 "-p, --params [cyan]<NAME VALUE> ...",44 "Query parameters to include in the request URL.",45 )46 table.add_row(47 "-c, --content [cyan]TEXT", "Byte content to include in the request body."48 )49 table.add_row(50 "-d, --data [cyan]<NAME VALUE> ...", "Form data to include in the request body."51 )52 table.add_row(53 "-f, --files [cyan]<NAME FILENAME> ...",54 "Form files to include in the request body.",55 )56 table.add_row("-j, --json [cyan]TEXT", "JSON data to include in the request body.")57 table.add_row(58 "-h, --headers [cyan]<NAME VALUE> ...",59 "Include additional HTTP headers in the request.",60 )61 table.add_row(62 "--cookies [cyan]<NAME VALUE> ...", "Cookies to include in the request."63 )64 table.add_row(65 "--auth [cyan]<USER PASS>",66 "Username and password to include in the request. Specify '-' for the password to use "67 "a password prompt. Note that using --verbose/-v will expose the Authorization "

Fix typo. (#1859)Tom Christiebefore adoptiond41840e

line 68why, one step back
68 "header, including the password encoding in a trivially reversible format.",

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 69–71why, one step back
69 )
7071 table.add_row(

Fix cli docs --proxies #2124 (#2125)kkbefore adoptionc82885a

line 72why, one step back
72 "--proxies [cyan]URL",

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 73–102why, one step back
73 "Send the request via a proxy. Should be the URL giving the proxy address.",
74 )7576 table.add_row(77 "--timeout [cyan]FLOAT",78 "Timeout value to use for network operations, such as establishing the connection, "79 "reading some data, etc... [Default: 5.0]",80 )8182 table.add_row("--follow-redirects", "Automatically follow redirects.")83 table.add_row("--no-verify", "Disable SSL verification.")84 table.add_row(85 "--http2", "Send the request using HTTP/2, if the remote server supports it."86 )8788 table.add_row(89 "--download [cyan]FILE",90 "Save the response content as a file, rather than displaying it.",91 )9293 table.add_row("-v, --verbose", "Verbose output. Show request as well as response.")94 table.add_row("--help", "Show this message and exit.")95 console.print(table)969798def get_lexer_for_response(response: Response) -> str:99 content_type = response.headers.get("Content-Type")100 if content_type is not None:101 mime_type, _, _ = content_type.partition(";")102 try:

Typing: enable warn_return_any (#2477)Martijn Pietersbefore adoption2d37321

lines 103–105why, one step back
103 return typing.cast(
104 str, pygments.lexers.get_lexer_for_mimetype(mime_type.strip()).name105 )

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 106why, one step back
106 except pygments.util.ClassNotFound: # pragma: no cover

Add cli support (#1855)Tom Christiebefore adoptionee9250d

line 107why, one step back
107 pass

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 108why, one step back
108 return "" # pragma: no cover

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 109–110why, one step back
109
110

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

line 111why, one step back
111def format_request_headers(request: httpcore.Request, http2: bool = False) -> str:

Tidy up the formatting of HTTP/2 requests (#1860)Tom Christiebefore adoptione1abaf1

lines 112–113why, one step back
112 version = "HTTP/2" if http2 else "HTTP/1.1"
113 headers = [

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

line 114why, one step back
114 (name.lower() if http2 else name, value) for name, value in request.headers

Tidy up the formatting of HTTP/2 requests (#1860)Tom Christiebefore adoptione1abaf1

line 115why, one step back
115 ]

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

lines 116–118why, one step back
116 method = request.method.decode("ascii")
117 target = request.url.target.decode("ascii")118 lines = [f"{method} {target} {version}"] + [

Tidy up the formatting of HTTP/2 requests (#1860)Tom Christiebefore adoptione1abaf1

line 119why, one step back
119 f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 120–123why, one step back
120 ]
121 return "\n".join(lines)122123

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

lines 124–137why, one step back
124def format_response_headers(
125 http_version: bytes,126 status: int,127 reason_phrase: typing.Optional[bytes],128 headers: typing.List[typing.Tuple[bytes, bytes]],129) -> str:130 version = http_version.decode("ascii")131 reason = (132 codes.get_reason_phrase(status)133 if reason_phrase is None134 else reason_phrase.decode("ascii")135 )136 lines = [f"{version} {status} {reason}"] + [137 f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 138–141why, one step back
138 ]
139 return "\n".join(lines)140141

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

line 142why, one step back
142def print_request_headers(request: httpcore.Request, http2: bool = False) -> None:

Add cli support (#1855)Tom Christiebefore adoptionee9250d

line 143why, one step back
143 console = rich.console.Console()

Tidy up the formatting of HTTP/2 requests (#1860)Tom Christiebefore adoptione1abaf1

line 144why, one step back
144 http_text = format_request_headers(request, http2=http2)

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 145–150why, one step back
145 syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True)
146 console.print(syntax)147 syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True)148 console.print(syntax)149150

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

lines 151–156why, one step back
151def print_response_headers(
152 http_version: bytes,153 status: int,154 reason_phrase: typing.Optional[bytes],155 headers: typing.List[typing.Tuple[bytes, bytes]],156) -> None:

Add cli support (#1855)Tom Christiebefore adoptionee9250d

line 157why, one step back
157 console = rich.console.Console()

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

line 158why, one step back
158 http_text = format_response_headers(http_version, status, reason_phrase, headers)

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 159–172why, one step back
159 syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True)
160 console.print(syntax)161 syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True)162 console.print(syntax)163164165def print_response(response: Response) -> None:166 console = rich.console.Console()167 lexer_name = get_lexer_for_response(response)168 if lexer_name:169 if lexer_name.lower() == "json":170 try:171 data = response.json()172 text = json.dumps(data, indent=4)

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 173why, one step back
173 except ValueError: # pragma: no cover

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 174–176why, one step back
174 text = response.text
175 else:176 text = response.text

Suppress binary output on the command line (#2049) (#2076)waterfountain1996before adoption4c30748

line 177why, one step back
177

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 178–179why, one step back
178 syntax = rich.syntax.Syntax(text, lexer_name, theme="ansi_dark", word_wrap=True)
179 console.print(syntax)

Suppress binary output on the command line (#2049) (#2076)waterfountain1996before adoption4c30748

lines 180–181why, one step back
180 else:
181 console.print(f"<{len(response.content)} bytes of binary data>")

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 182–183why, one step back
182
183

Typing: always fill in generic type parameters (#2468)Adrian Garcia Badaraccobefore adoption1b4e7fb

lines 184–189why, one step back
184_PCTRTT = typing.Tuple[typing.Tuple[str, str], ...]
185_PCTRTTT = typing.Tuple[_PCTRTT, ...]186_PeerCertRetDictType = typing.Dict[str, typing.Union[str, _PCTRTTT, _PCTRTT]]187188189def format_certificate(cert: _PeerCertRetDictType) -> str: # pragma: no cover

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

lines 190–206why, one step back
190 lines = []
191 for key, value in cert.items():192 if isinstance(value, (list, tuple)):193 lines.append(f"* {key}:")194 for item in value:195 if key in ("subject", "issuer"):196 for sub_item in item:197 lines.append(f"* {sub_item[0]}: {sub_item[1]!r}")198 elif isinstance(item, tuple) and len(item) == 2:199 lines.append(f"* {item[0]}: {item[1]!r}")200 else:201 lines.append(f"* {item!r}")202 else:203 lines.append(f"* {key}: {value!r}")204 return "\n".join(lines)205206

add basic type annotation for RequestExtensions and RequestData (#2367)Adrian Garcia Badaraccobefore adoption8152c4f

lines 207–209why, one step back
207def trace(
208 name: str, info: typing.Mapping[str, typing.Any], verbose: bool = False209) -> None:

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

lines 210–217why, one step back
210 console = rich.console.Console()
211 if name == "connection.connect_tcp.started" and verbose:212 host = info["host"]213 console.print(f"* Connecting to {host!r}")214 elif name == "connection.connect_tcp.complete" and verbose:215 stream = info["return_value"]216 server_addr = stream.get_extra_info("server_addr")217 console.print(f"* Connected to {server_addr[0]!r} on port {server_addr[1]}")

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 218why, one step back
218 elif name == "connection.start_tls.complete" and verbose: # pragma: no cover

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

lines 219–232why, one step back
219 stream = info["return_value"]
220 ssl_object = stream.get_extra_info("ssl_object")221 version = ssl_object.version()222 cipher = ssl_object.cipher()223 server_cert = ssl_object.getpeercert()224 alpn = ssl_object.selected_alpn_protocol()225 console.print(f"* SSL established using {version!r} / {cipher[0]!r}")226 console.print(f"* Selected ALPN protocol: {alpn!r}")227 if server_cert:228 console.print("* Server certificate:")229 console.print(format_certificate(server_cert))230 elif name == "http11.send_request_headers.started" and verbose:231 request = info["request"]232 print_request_headers(request, http2=False)

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 233why, one step back
233 elif name == "http2.send_request_headers.started" and verbose: # pragma: no cover

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

lines 234–238why, one step back
234 request = info["request"]
235 print_request_headers(request, http2=True)236 elif name == "http11.receive_response_headers.complete":237 http_version, status, reason_phrase, headers = info["return_value"]238 print_response_headers(http_version, status, reason_phrase, headers)

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 239why, one step back
239 elif name == "http2.receive_response_headers.complete": # pragma: no cover

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

lines 240–245why, one step back
240 status, headers = info["return_value"]
241 http_version = b"HTTP/2"242 reason_phrase = None243 print_response_headers(http_version, status, reason_phrase, headers)244245

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 246–247why, one step back
246def download_response(response: Response, download: typing.BinaryIO) -> None:
247 console = rich.console.Console()

Fix console markup escaping issue (#1866)Will McGuganbefore adoption2814fd3

line 248why, one step back
248 console.print()

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 249–256why, one step back
249 content_length = response.headers.get("Content-Length")
250 with rich.progress.Progress(251 "[progress.description]{task.description}",252 "[progress.percentage]{task.percentage:>3.0f}%",253 rich.progress.BarColumn(bar_width=None),254 rich.progress.DownloadColumn(),255 rich.progress.TransferSpeedColumn(),256 ) as progress:

Fix console markup escaping issue (#1866)Will McGuganbefore adoption2814fd3

lines 257–262why, one step back
257 description = f"Downloading [bold]{rich.markup.escape(download.name)}"
258 download_task = progress.add_task(259 description,260 total=int(content_length or 0),261 start=content_length is not None,262 )

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 263–277why, one step back
263 for chunk in response.iter_bytes():
264 download.write(chunk)265 progress.update(download_task, completed=response.num_bytes_downloaded)266267268def validate_json(269 ctx: click.Context,270 param: typing.Union[click.Option, click.Parameter],271 value: typing.Any,272) -> typing.Any:273 if value is None:274 return None275276 try:277 return json.loads(value)

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 278why, one step back
278 except json.JSONDecodeError: # pragma: no cover

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 279–290why, one step back
279 raise click.BadParameter("Not valid JSON")
280281282def validate_auth(283 ctx: click.Context,284 param: typing.Union[click.Option, click.Parameter],285 value: typing.Any,286) -> typing.Any:287 if value == (None, None):288 return None289290 username, password = value

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 291why, one step back
291 if password == "-": # pragma: no cover

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 292–383why, one step back
292 password = click.prompt("Password", hide_input=True)
293 return (username, password)294295296def handle_help(297 ctx: click.Context,298 param: typing.Union[click.Option, click.Parameter],299 value: typing.Any,300) -> None:301 if not value or ctx.resilient_parsing:302 return303304 print_help()305 ctx.exit()306307308@click.command(add_help_option=False)309@click.argument("url", type=str)310@click.option(311 "--method",312 "-m",313 "method",314 type=str,315 help=(316 "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD. "317 "[Default: GET, or POST if a request body is included]"318 ),319)320@click.option(321 "--params",322 "-p",323 "params",324 type=(str, str),325 multiple=True,326 help="Query parameters to include in the request URL.",327)328@click.option(329 "--content",330 "-c",331 "content",332 type=str,333 help="Byte content to include in the request body.",334)335@click.option(336 "--data",337 "-d",338 "data",339 type=(str, str),340 multiple=True,341 help="Form data to include in the request body.",342)343@click.option(344 "--files",345 "-f",346 "files",347 type=(str, click.File(mode="rb")),348 multiple=True,349 help="Form files to include in the request body.",350)351@click.option(352 "--json",353 "-j",354 "json",355 type=str,356 callback=validate_json,357 help="JSON data to include in the request body.",358)359@click.option(360 "--headers",361 "-h",362 "headers",363 type=(str, str),364 multiple=True,365 help="Include additional HTTP headers in the request.",366)367@click.option(368 "--cookies",369 "cookies",370 type=(str, str),371 multiple=True,372 help="Cookies to include in the request.",373)374@click.option(375 "--auth",376 "auth",377 type=(str, str),378 default=(None, None),379 callback=validate_auth,380 help=(381 "Username and password to include in the request. "382 "Specify '-' for the password to use a password prompt. "383 "Note that using --verbose/-v will expose the Authorization header, "

Fix typo. (#1859)Tom Christiebefore adoptiond41840e

line 384why, one step back
384 "including the password encoding in a trivially reversible format."

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 385–491why, one step back
385 ),
386)387@click.option(388 "--proxies",389 "proxies",390 type=str,391 default=None,392 help="Send the request via a proxy. Should be the URL giving the proxy address.",393)394@click.option(395 "--timeout",396 "timeout",397 type=float,398 default=5.0,399 help=(400 "Timeout value to use for network operations, such as establishing the "401 "connection, reading some data, etc... [Default: 5.0]"402 ),403)404@click.option(405 "--follow-redirects",406 "follow_redirects",407 is_flag=True,408 default=False,409 help="Automatically follow redirects.",410)411@click.option(412 "--no-verify",413 "verify",414 is_flag=True,415 default=True,416 help="Disable SSL verification.",417)418@click.option(419 "--http2",420 "http2",421 type=bool,422 is_flag=True,423 default=False,424 help="Send the request using HTTP/2, if the remote server supports it.",425)426@click.option(427 "--download",428 type=click.File("wb"),429 help="Save the response content as a file, rather than displaying it.",430)431@click.option(432 "--verbose",433 "-v",434 type=bool,435 is_flag=True,436 default=False,437 help="Verbose. Show request as well as response.",438)439@click.option(440 "--help",441 is_flag=True,442 is_eager=True,443 expose_value=False,444 callback=handle_help,445 help="Show this message and exit.",446)447def main(448 url: str,449 method: str,450 params: typing.List[typing.Tuple[str, str]],451 content: str,452 data: typing.List[typing.Tuple[str, str]],453 files: typing.List[typing.Tuple[str, click.File]],454 json: str,455 headers: typing.List[typing.Tuple[str, str]],456 cookies: typing.List[typing.Tuple[str, str]],457 auth: typing.Optional[typing.Tuple[str, str]],458 proxies: str,459 timeout: float,460 follow_redirects: bool,461 verify: bool,462 http2: bool,463 download: typing.Optional[typing.BinaryIO],464 verbose: bool,465) -> None:466 """467 An HTTP command line client.468 Sends a request and displays the response.469 """470 if not method:471 method = "POST" if content or data or files or json else "GET"472473 try:474 with Client(475 proxies=proxies,476 timeout=timeout,477 verify=verify,478 http2=http2,479 ) as client:480 with client.stream(481 method,482 url,483 params=list(params),484 content=content,485 data=dict(data),486 files=files, # type: ignore487 json=json,488 headers=headers,489 cookies=dict(cookies),490 auth=auth,491 follow_redirects=follow_redirects,

Version 0.21 (#1935)Tom Christiebefore adoption61188fe

line 492why, one step back
492 extensions={"trace": functools.partial(trace, verbose=verbose)},

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 493–502why, one step back
493 ) as response:
494 if download is not None:495 download_response(response, download)496 else:497 response.read()498 if response.content:499 print_response(response)500501 except RequestError as exc:502 console = rich.console.Console()

Tiny refactor on _multipart.py & _main.py (#1971)Mohammadreza Jafaribefore adoption83c81aa

line 503why, one step back
503 console.print(f"[red]{type(exc).__name__}[/red]: {exc}")

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 504–506why, one step back
504 sys.exit(1)
505506 sys.exit(0 if response.is_success else 1)