Skip to content
Myr

Add cli support (#1855)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Add cli support * Add setup.py * Import main to 'httpx.main' * Add 'cli' to requirements * Add tests for command-line client * Drop most CLI tests * Add test_json * Add test_redirects * Coverage exclusion over _main.py in order to test more clearly * Black formatting * Add test_follow_redirects * Add test_post, test_verbose, test_auth * Add test_errors * Remove test_errors * Add test_download * Change test_errors - perhaps the empty host header was causing the socket error? * Update test_errors to not break socket * Update docs * Update version to 1.0.0.beta0 * Tweak CHANGELOG * Fix up images in README * Tweak images in README * Update README

authored by Tom Christie · committed by GitHub · parent a761e17 · Browse files · 14 files+796 added−67 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

14 files+796 added−67 removed

  • tests:+178 added−0 removed
  • other:+618 added−67 removed

14 files+796 added−67 removed

added:docs/img/httpx-help.pngbinary

A binary file, added.

added:docs/img/httpx-request.pngbinary

A binary file, added.

modified:docs/compatibility.md+35 added-27 removed
1# Requests Compatibility Guide23HTTPX aims to be broadly compatible with the `requests` API.3HTTPX aims to be broadly compatible with the `requests` API, although there are a4few design differences in places.56This documentation outlines places where the API differs...77## Client instances89The HTTPX equivalent of `requests.Session` is `httpx.Client`.1011```python12session = requests.Session(**kwargs)13```1415is generally equivalent to1617```python18client = httpx.Client(**kwargs)19```2021## Request URLs2223Accessing `response.url` will return a `URL` instance, rather than a string.2425Use `str(response.url)` if you need a string instance.268## Redirects910Unlike `requests`, HTTPX does **not follow redirects by default**.11
12 unmodified lines
24```python25client = httpx.Client(follow_redirects=True)26```2728## Client instances2930The HTTPX equivalent of `requests.Session` is `httpx.Client`.3132```python33session = requests.Session(**kwargs)34```3536is generally equivalent to3738```python39client = httpx.Client(**kwargs)40```4142## Request URLs4344Accessing `response.url` will return a `URL` instance, rather than a string.4546Use `str(response.url)` if you need a string instance.4748## Determining the next redirect request4950The `requests` library exposes an attribute `response.next`, which can be used to obtain the next redirect request.51
45 unmodified lines
9798## Content encoding99100HTTPX uses `utf-8` for encoding `str` request bodies. For example, when using `content=<str>` the request body will be encoded to `utf-8` before being sent over the wire. This differs from Requests which uses `latin1`. If you need an explicit encoding, pass encoded bytes explictly, e.g. `content=<str>.encode("latin1")`.101For response bodies, assuming the server didn't send an explicit encoding then HTTPX will do its best to figure out an appropriate encoding. HTTPX makes a guess at the encoding to use for decoding the response using `charset_normalizer`. Fallback to that or any content with less than 32 octets will be decoded using `utf-8` with the `error="replace"` decoder strategy.102101For response bodies, assuming the server didn't send an explicit encoding then HTTPX will do its best to figure out an appropriate encoding. HTTPX makes a guess at the encoding to use for decoding the response using `charset_normalizer`. Fallback to that or any content with less than 32 octets will be decoded using `utf-8` with the `error="replace"` decoder strategy. 102103## Cookies104105If using a client instance, then cookies should always be set on the client rather than on a per-request basis.106
25 unmodified lines
132133For example:134135```python136with request.stream("GET", "https://www.example.com") as response:136with httpx.stream("GET", "https://www.example.com") as response:137 ...138```139140Within a `stream()` block request data is made available with:
23 unmodified lines
164Requests supports `REQUESTS_CA_BUNDLE` which points to either a file or a directory. HTTPX supports the `SSL_CERT_FILE` (for a file) and `SSL_CERT_DIR` (for a directory) OpenSSL variables instead.165166## Request body on HTTP methods167168The HTTP `GET`, `DELETE`, `HEAD`, and `OPTIONS` methods are specified as not supporting a request body. To stay in line with this, the `.get`, `.delete`, `.head` and `.options` functions do not support `files`, `data`, or `json` arguments.168The HTTP `GET`, `DELETE`, `HEAD`, and `OPTIONS` methods are specified as not supporting a request body. To stay in line with this, the `.get`, `.delete`, `.head` and `.options` functions do not support `content`, `files`, `data`, or `json` arguments.169170If you really do need to send request data using these http methods you should use the generic `.request` function instead.171172## Checking for 4xx/5xx responses172```python173httpx.request(174 method="DELETE",175 url="https://www.example.com/",176 content=b'A request body on a DELETE request.'177)178```179174We don't support `response.is_ok` since the naming is ambiguous there, and might incorrectly imply an equivalence to `response.status_code == codes.OK`. Instead we provide the `response.is_error` property. Use `if not response.is_error:` instead of `if response.is_ok:`.180## Checking for success and failure responses181182We don't support `response.is_ok` since the naming is ambiguous there, and might incorrectly imply an equivalence to `response.status_code == codes.OK`. Instead we provide the `response.is_success` property, which can be used to check for a 2xx response.183184## Request instantiation185186There is no notion of [prepared requests](https://requests.readthedocs.io/en/stable/user/advanced/#prepared-requests) in HTTPX. If you need to customize request instantiation, see [Request instances](advanced.md#request-instances).187
23 unmodified lines
modified:docs/index.md+22 added-17 removed
modified:docs/quickstart.md+2 added-5 removed
71 unmodified lines
72'UTF-8'73```7475In some cases the response may not contain an explicit encoding, in which case HTTPX76will attempt to automatically determine an encoding to use. This defaults to77UTF-8, but also includes robust fallback behaviour for handling ascii,78iso-8859-1 and windows 1252 encodings.76will attempt to automatically determine an encoding to use.7778```pycon79>>> r.encoding80None81>>> r.text82'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'83```848785If you need to override the standard behaviour and explicitly set the encoding to86use, then you can do that too.8788```pycon
184 unmodified lines
273>>> r.status_code == httpx.codes.OK274True275```276280We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):277We can raise an exception for any responses which are not a 2xx success code:278279```pycon280>>> not_found = httpx.get('https://httpbin.org/status/404')281>>> not_found.status_code
200 unmodified lines
modified:httpx/__init__.py+16 added
41 unmodified lines
42from ._transports.mock import MockTransport43from ._transports.wsgi import WSGITransport44from ._types import AsyncByteStream, SyncByteStream4546try:47 from ._main import main48except ImportError: # pragma: nocover4950 def main() -> None: # type: ignore51 import sys5253 print(54 "The httpx command line client could not run because the required "55 "dependencies were not installed.\nMake sure you've installed "56 "everything with: pip install 'httpx[cli]'"57 )58 sys.exit(1)596061__all__ = [62 "__description__",63 "__title__",64 "__version__",
25 unmodified lines
90 "HTTPTransport",91 "InvalidURL",92 "Limits",93 "LocalProtocolError",94 "main",95 "MockTransport",96 "NetworkError",97 "options",98 "patch",
38 unmodified lines
modified:httpx/__version__.py+1 added-1 removed
1__title__ = "httpx"2__description__ = "A next generation HTTP client, for Python 3."3__version__ = "0.19.0"3__version__ = "1.0.0.beta0"
added:httpx/_main.py+438 added
1import json2import sys3import typing45import click6import pygments.lexers7import pygments.util8import rich.console9import rich.progress10import rich.syntax1112from ._client import Client13from ._exceptions import RequestError14from ._models import Request, Response151617def print_help() -> None:18 console = rich.console.Console()1920 console.print("[bold]HTTPX :butterfly:", justify="center")21 console.print()22 console.print("A next generation HTTP client.", justify="center")23 console.print()24 console.print(25 "Usage: [bold]httpx[/bold] [cyan]<URL> [OPTIONS][/cyan] ", justify="left"26 )27 console.print()2829 table = rich.table.Table.grid(padding=1, pad_edge=True)30 table.add_column("Parameter", no_wrap=True, justify="left", style="bold")31 table.add_column("Description")32 table.add_row(33 "-m, --method [cyan]METHOD",34 "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.\n"35 "[Default: GET, or POST if a request body is included]",36 )37 table.add_row(38 "-p, --params [cyan]<NAME VALUE> ...",39 "Query parameters to include in the request URL.",40 )41 table.add_row(42 "-c, --content [cyan]TEXT", "Byte content to include in the request body."43 )44 table.add_row(45 "-d, --data [cyan]<NAME VALUE> ...", "Form data to include in the request body."46 )47 table.add_row(48 "-f, --files [cyan]<NAME FILENAME> ...",49 "Form files to include in the request body.",50 )51 table.add_row("-j, --json [cyan]TEXT", "JSON data to include in the request body.")52 table.add_row(53 "-h, --headers [cyan]<NAME VALUE> ...",54 "Include additional HTTP headers in the request.",55 )56 table.add_row(57 "--cookies [cyan]<NAME VALUE> ...", "Cookies to include in the request."58 )59 table.add_row(60 "--auth [cyan]<USER PASS>",61 "Username and password to include in the request. Specify '-' for the password to use "62 "a password prompt. Note that using --verbose/-v will expose the Authorization "63 "header, including the password encoding in a trivially reverisible format.",64 )6566 table.add_row(67 "--proxy [cyan]URL",68 "Send the request via a proxy. Should be the URL giving the proxy address.",69 )7071 table.add_row(72 "--timeout [cyan]FLOAT",73 "Timeout value to use for network operations, such as establishing the connection, "74 "reading some data, etc... [Default: 5.0]",75 )7677 table.add_row("--follow-redirects", "Automatically follow redirects.")78 table.add_row("--no-verify", "Disable SSL verification.")79 table.add_row(80 "--http2", "Send the request using HTTP/2, if the remote server supports it."81 )8283 table.add_row(84 "--download [cyan]FILE",85 "Save the response content as a file, rather than displaying it.",86 )8788 table.add_row("-v, --verbose", "Verbose output. Show request as well as response.")89 table.add_row("--help", "Show this message and exit.")90 console.print(table)919293def get_lexer_for_response(response: Response) -> str:94 content_type = response.headers.get("Content-Type")95 if content_type is not None:96 mime_type, _, _ = content_type.partition(";")97 try:98 return pygments.lexers.get_lexer_for_mimetype(mime_type.strip()).name99 except pygments.util.ClassNotFound: # pragma: nocover100 pass101 return "" # pragma: nocover102103104def format_request_headers(request: Request) -> str:105 target = request.url.raw[-1].decode("ascii")106 lines = [f"{request.method} {target} HTTP/1.1"] + [107 f"{name.decode('ascii')}: {value.decode('ascii')}"108 for name, value in request.headers.raw109 ]110 return "\n".join(lines)111112113def format_response_headers(response: Response) -> str:114 lines = [115 f"{response.http_version} {response.status_code} {response.reason_phrase}"116 ] + [117 f"{name.decode('ascii')}: {value.decode('ascii')}"118 for name, value in response.headers.raw119 ]120 return "\n".join(lines)121122123def print_request_headers(request: Request) -> None:124 console = rich.console.Console()125 http_text = format_request_headers(request)126 syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True)127 console.print(syntax)128 syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True)129 console.print(syntax)130131132def print_response_headers(response: Response) -> None:133 console = rich.console.Console()134 http_text = format_response_headers(response)135 syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True)136 console.print(syntax)137138139def print_delimiter() -> None:140 console = rich.console.Console()141 syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True)142 console.print(syntax)143144145def print_redirects(response: Response) -> None:146 if response.has_redirect_location:147 response.read()148 print_response_headers(response)149 print_response(response)150151152def print_response(response: Response) -> None:153 console = rich.console.Console()154 lexer_name = get_lexer_for_response(response)155 if lexer_name:156 if lexer_name.lower() == "json":157 try:158 data = response.json()159 text = json.dumps(data, indent=4)160 except ValueError: # pragma: nocover161 text = response.text162 else:163 text = response.text164 syntax = rich.syntax.Syntax(text, lexer_name, theme="ansi_dark", word_wrap=True)165 console.print(syntax)166 else: # pragma: nocover167 console.print(response.text)168169170def download_response(response: Response, download: typing.BinaryIO) -> None:171 console = rich.console.Console()172 syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True)173 console.print(syntax)174175 content_length = response.headers.get("Content-Length")176 kwargs = {"total": int(content_length)} if content_length else {}177 with rich.progress.Progress(178 "[progress.description]{task.description}",179 "[progress.percentage]{task.percentage:>3.0f}%",180 rich.progress.BarColumn(bar_width=None),181 rich.progress.DownloadColumn(),182 rich.progress.TransferSpeedColumn(),183 ) as progress:184 description = f"Downloading [bold]{download.name}"185 download_task = progress.add_task(description, **kwargs) # type: ignore186 for chunk in response.iter_bytes():187 download.write(chunk)188 progress.update(download_task, completed=response.num_bytes_downloaded)189190191def validate_json(192 ctx: click.Context,193 param: typing.Union[click.Option, click.Parameter],194 value: typing.Any,195) -> typing.Any:196 if value is None:197 return None198199 try:200 return json.loads(value)201 except json.JSONDecodeError: # pragma: nocover202 raise click.BadParameter("Not valid JSON")203204205def validate_auth(206 ctx: click.Context,207 param: typing.Union[click.Option, click.Parameter],208 value: typing.Any,209) -> typing.Any:210 if value == (None, None):211 return None212213 username, password = value214 if password == "-": # pragma: nocover215 password = click.prompt("Password", hide_input=True)216 return (username, password)217218219def handle_help(220 ctx: click.Context,221 param: typing.Union[click.Option, click.Parameter],222 value: typing.Any,223) -> None:224 if not value or ctx.resilient_parsing:225 return226227 print_help()228 ctx.exit()229230231@click.command(add_help_option=False)232@click.argument("url", type=str)233@click.option(234 "--method",235 "-m",236 "method",237 type=str,238 help=(239 "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD. "240 "[Default: GET, or POST if a request body is included]"241 ),242)243@click.option(244 "--params",245 "-p",246 "params",247 type=(str, str),248 multiple=True,249 help="Query parameters to include in the request URL.",250)251@click.option(252 "--content",253 "-c",254 "content",255 type=str,256 help="Byte content to include in the request body.",257)258@click.option(259 "--data",260 "-d",261 "data",262 type=(str, str),263 multiple=True,264 help="Form data to include in the request body.",265)266@click.option(267 "--files",268 "-f",269 "files",270 type=(str, click.File(mode="rb")),271 multiple=True,272 help="Form files to include in the request body.",273)274@click.option(275 "--json",276 "-j",277 "json",278 type=str,279 callback=validate_json,280 help="JSON data to include in the request body.",281)282@click.option(283 "--headers",284 "-h",285 "headers",286 type=(str, str),287 multiple=True,288 help="Include additional HTTP headers in the request.",289)290@click.option(291 "--cookies",292 "cookies",293 type=(str, str),294 multiple=True,295 help="Cookies to include in the request.",296)297@click.option(298 "--auth",299 "auth",300 type=(str, str),301 default=(None, None),302 callback=validate_auth,303 help=(304 "Username and password to include in the request. "305 "Specify '-' for the password to use a password prompt. "306 "Note that using --verbose/-v will expose the Authorization header, "307 "including the password encoding in a trivially reverisible format."308 ),309)310@click.option(311 "--proxies",312 "proxies",313 type=str,314 default=None,315 help="Send the request via a proxy. Should be the URL giving the proxy address.",316)317@click.option(318 "--timeout",319 "timeout",320 type=float,321 default=5.0,322 help=(323 "Timeout value to use for network operations, such as establishing the "324 "connection, reading some data, etc... [Default: 5.0]"325 ),326)327@click.option(328 "--follow-redirects",329 "follow_redirects",330 is_flag=True,331 default=False,332 help="Automatically follow redirects.",333)334@click.option(335 "--no-verify",336 "verify",337 is_flag=True,338 default=True,339 help="Disable SSL verification.",340)341@click.option(342 "--http2",343 "http2",344 type=bool,345 is_flag=True,346 default=False,347 help="Send the request using HTTP/2, if the remote server supports it.",348)349@click.option(350 "--download",351 type=click.File("wb"),352 help="Save the response content as a file, rather than displaying it.",353)354@click.option(355 "--verbose",356 "-v",357 type=bool,358 is_flag=True,359 default=False,360 help="Verbose. Show request as well as response.",361)362@click.option(363 "--help",364 is_flag=True,365 is_eager=True,366 expose_value=False,367 callback=handle_help,368 help="Show this message and exit.",369)370def main(371 url: str,372 method: str,373 params: typing.List[typing.Tuple[str, str]],374 content: str,375 data: typing.List[typing.Tuple[str, str]],376 files: typing.List[typing.Tuple[str, click.File]],377 json: str,378 headers: typing.List[typing.Tuple[str, str]],379 cookies: typing.List[typing.Tuple[str, str]],380 auth: typing.Optional[typing.Tuple[str, str]],381 proxies: str,382 timeout: float,383 follow_redirects: bool,384 verify: bool,385 http2: bool,386 download: typing.Optional[typing.BinaryIO],387 verbose: bool,388) -> None:389 """390 An HTTP command line client.391 Sends a request and displays the response.392 """393 if not method:394 method = "POST" if content or data or files or json else "GET"395396 event_hooks: typing.Dict[str, typing.List[typing.Callable]] = {}397 if verbose:398 event_hooks["request"] = [print_request_headers]399 if follow_redirects:400 event_hooks["response"] = [print_redirects]401402 try:403 with Client(404 proxies=proxies,405 timeout=timeout,406 verify=verify,407 http2=http2,408 event_hooks=event_hooks,409 ) as client:410 with client.stream(411 method,412 url,413 params=list(params),414 content=content,415 data=dict(data),416 files=files, # type: ignore417 json=json,418 headers=headers,419 cookies=dict(cookies),420 auth=auth,421 follow_redirects=follow_redirects,422 ) as response:423 print_response_headers(response)424425 if download is not None:426 download_response(response, download)427 else:428 response.read()429 if response.content:430 print_delimiter()431 print_response(response)432433 except RequestError as exc:434 console = rich.console.Console()435 console.print(f"{type(exc).__name__}: {exc}")436 sys.exit(1)437438 sys.exit(0 if response.is_success else 1)
modified:tests/conftest.py+13 added
82 unmodified lines
83 elif scope["path"].startswith("/echo_headers"):84 await echo_headers(scope, receive, send)85 elif scope["path"].startswith("/redirect_301"):86 await redirect_301(scope, receive, send)87 elif scope["path"].startswith("/json"):88 await hello_world_json(scope, receive, send)89 else:90 await hello_world(scope, receive, send)9192
7 unmodified lines
100 )101 await send({"type": "http.response.body", "body": b"Hello, world!"})102103104async def hello_world_json(scope, receive, send):105 await send(106 {107 "type": "http.response.start",108 "status": 200,109 "headers": [[b"content-type", b"application/json"]],110 }111 )112 await send({"type": "http.response.body", "body": b'{"Hello": "world!"}'})113114115async def slow_response(scope, receive, send):116 await sleep(1.0)117 await send(118 {
184 unmodified lines
added:tests/test_main.py+165 added
1import os23from click.testing import CliRunner45import httpx678def splitlines(output):9 return [line.strip() for line in output.splitlines()]101112def remove_date_header(lines):13 return [line for line in lines if not line.startswith("date:")]141516def test_help():17 runner = CliRunner()18 result = runner.invoke(httpx.main, ["--help"])19 assert result.exit_code == 020 assert "A next generation HTTP client." in result.output212223def test_get(server):24 url = str(server.url)25 runner = CliRunner()26 result = runner.invoke(httpx.main, [url])27 assert result.exit_code == 028 assert remove_date_header(splitlines(result.output)) == [29 "HTTP/1.1 200 OK",30 "server: uvicorn",31 "content-type: text/plain",32 "Transfer-Encoding: chunked",33 "",34 "Hello, world!",35 ]363738def test_json(server):39 url = str(server.url.copy_with(path="/json"))40 runner = CliRunner()41 result = runner.invoke(httpx.main, [url])42 assert result.exit_code == 043 assert remove_date_header(splitlines(result.output)) == [44 "HTTP/1.1 200 OK",45 "server: uvicorn",46 "content-type: application/json",47 "Transfer-Encoding: chunked",48 "",49 "{",50 '"Hello": "world!"',51 "}",52 ]535455def test_redirects(server):56 url = str(server.url.copy_with(path="/redirect_301"))57 runner = CliRunner()58 result = runner.invoke(httpx.main, [url])59 assert result.exit_code == 160 assert remove_date_header(splitlines(result.output)) == [61 "HTTP/1.1 301 Moved Permanently",62 "server: uvicorn",63 "location: /",64 "Transfer-Encoding: chunked",65 ]666768def test_follow_redirects(server):69 url = str(server.url.copy_with(path="/redirect_301"))70 runner = CliRunner()71 result = runner.invoke(httpx.main, [url, "--follow-redirects"])72 assert result.exit_code == 073 assert remove_date_header(splitlines(result.output)) == [74 "HTTP/1.1 301 Moved Permanently",75 "server: uvicorn",76 "location: /",77 "Transfer-Encoding: chunked",78 "",79 "HTTP/1.1 200 OK",80 "server: uvicorn",81 "content-type: text/plain",82 "Transfer-Encoding: chunked",83 "",84 "Hello, world!",85 ]868788def test_post(server):89 url = str(server.url.copy_with(path="/echo_body"))90 runner = CliRunner()91 result = runner.invoke(httpx.main, [url, "-m", "POST", "-j", '{"hello": "world"}'])92 assert result.exit_code == 093 assert remove_date_header(splitlines(result.output)) == [94 "HTTP/1.1 200 OK",95 "server: uvicorn",96 "content-type: text/plain",97 "Transfer-Encoding: chunked",98 "",99 '{"hello": "world"}',100 ]101102103def test_verbose(server):104 url = str(server.url)105 runner = CliRunner()106 result = runner.invoke(httpx.main, [url, "-v"])107 assert result.exit_code == 0108 assert remove_date_header(splitlines(result.output)) == [109 "GET / HTTP/1.1",110 f"Host: {server.url.netloc.decode('ascii')}",111 "Accept: */*",112 "Accept-Encoding: gzip, deflate, br",113 "Connection: keep-alive",114 f"User-Agent: python-httpx/{httpx.__version__}",115 "",116 "HTTP/1.1 200 OK",117 "server: uvicorn",118 "content-type: text/plain",119 "Transfer-Encoding: chunked",120 "",121 "Hello, world!",122 ]123124125def test_auth(server):126 url = str(server.url)127 runner = CliRunner()128 result = runner.invoke(httpx.main, [url, "-v", "--auth", "username", "password"])129 print(result.output)130 assert result.exit_code == 0131 assert remove_date_header(splitlines(result.output)) == [132 "GET / HTTP/1.1",133 f"Host: {server.url.netloc.decode('ascii')}",134 "Accept: */*",135 "Accept-Encoding: gzip, deflate, br",136 "Connection: keep-alive",137 f"User-Agent: python-httpx/{httpx.__version__}",138 "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=",139 "",140 "HTTP/1.1 200 OK",141 "server: uvicorn",142 "content-type: text/plain",143 "Transfer-Encoding: chunked",144 "",145 "Hello, world!",146 ]147148149def test_download(server):150 url = str(server.url)151 runner = CliRunner()152 with runner.isolated_filesystem():153 runner.invoke(httpx.main, [url, "--download", "index.txt"])154 assert os.path.exists("index.txt")155 with open("index.txt", "r") as input_file:156 assert input_file.read() == "Hello, world!"157158159def test_errors():160 runner = CliRunner()161 result = runner.invoke(httpx.main, ["invalid://example.org"])162 assert result.exit_code == 1163 assert splitlines(result.output) == [164 "UnsupportedProtocol: Request URL has an unsupported protocol 'invalid://'.",165 ]
modified:CHANGELOG.md+67 added
2 unmodified lines
3All notable changes to this project will be documented in this file.45The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).67## 1.0.0.beta089The 1.0 pre-release adds an integrated command-line client, and also includes some10design changes. The most notable of these is that redirect responses are no longer11automatically followed, unless specifically requested.1213This design decision prioritises a more explicit approach to redirects, in order14to avoid code that unintentionally issues multiple requests as a result of15misconfigured URLs.1617For example, previously a client configured to send requests to `http://api.github.com/`18would end up sending every API request twice, as each request would be redirected to `https://api.github.com/`.1920If you do want auto-redirect behaviour, you can enable this either by configuring21the client instance with `Client(follow_redirects=True)`, or on a per-request22basis, with `.get(..., follow_redirects=True)`.2324This change is a classic trade-off between convenience and precision, with no "right"25answer. See [discussion #1785](https://github.com/encode/httpx/discussions/1785) for more26context.2728The other major design change is an update to the Transport API, which is the low-level29interface against which requests are sent. Previously this interface used only primitive30datastructures, like so...3132```python33(status_code, headers, stream, extensions) = transport.handle_request(method, url, headers, stream, extensions)34try35 ...36finally:37 stream.close()38```3940Now the interface is much simpler...4142```python43response = transport.handle_request(request)44try45 ...46finally:47 response.close()48```4950### Changed5152* The `allow_redirects` flag is now `follow_redirects` and defaults to `False`.53* The `raise_for_status()` method will now raise an exception for any responses54 except those with 2xx status codes. Previously only 4xx and 5xx status codes55 would result in an exception.56* The low-level transport API changes to the much simpler `response = transport.handle_request(request)`.57* The `client.send()` method no longer accepts a `timeout=...` argument, but the58 `client.build_request()` does. This required by the signature change of the59 Transport API. The request timeout configuration is now stored on the request60 instance, as `request.extensions['timeout']`.6162### Added6364* Added the `httpx` command-line client.65* Response instances now include `.is_informational`, `.is_success`, `.is_redirect`, `.is_client_error`, and `.is_server_error`66 properties for checking 1xx, 2xx, 3xx, 4xx, and 5xx response types. Note that the behaviour of `.is_redirect` is slightly different in that it now returns True for all 3xx responses, in order to allow for a consistent set of properties onto the different HTTP status code types. The `response.has_redirect_location` location may be used to determine responses with properly formed URL redirects.6768### Fixed6970* `response.iter_bytes()` no longer raises a ValueError when called on a response with no content. (Pull #1827)71* The `'wsgi.error'` configuration now defaults to `sys.stderr`, and is corrected to be a `TextIO` interface, not a `BytesIO` interface. Additionally, the WSGITransport now accepts a `wsgi_error` confguration. (Pull #1828)72* Follow the WSGI spec by properly closing the iterable returned by the application. (Pull #1830)7374## 0.19.0 (19th August, 2021)7576### Added77
801 unmodified lines
modified:README.md+28 added-16 removed
11 unmodified lines
12 <img src="https://badge.fury.io/py/httpx.svg" alt="Package version">13</a>14</p>1516HTTPX is a fully featured HTTP client for Python 3, which provides sync and async APIs, and support for both HTTP/1.1 and HTTP/2.16HTTPX is a fully featured HTTP client library for Python 3. It includes **an integrated17command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync18and async APIs**.1918**Note**: _HTTPX should be considered in beta. We believe we've got the public API to19a stable point now, but would strongly recommend pinning your dependencies to the `0.19.*`20release, so that you're able to properly review [API changes between package updates](https://github.com/encode/httpx/blob/master/CHANGELOG.md). A 1.0 release is expected to be issued sometime in 2021._20**Note**: *This is the README for the 1.0 pre-release. This release adds support for an integrated command-line client, and also includes a couple of design changes from 0.19. Redirects are no longer followed by default, and the low-level Transport API has been updated. Upgrades from 0.19 will need to see [the CHANGELOG](https://github.com/encode/httpx/blob/version-1.0/CHANGELOG.md) for more details.*2122---2324Let's get started...24Installing HTTPX.2526```shell27$ pip install httpx --pre28```2930Now, let's get started...3132```pycon33>>> import httpx34>>> r = httpx.get('https://www.example.org/')35>>> r
5 unmodified lines
41>>> r.text42'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'43```4439Or, using the async API...45Or, using the command-line client.4641_Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.8+ with `python -m asyncio` to try this code interactively._4243```pycon44>>> import httpx45>>> async with httpx.AsyncClient() as client:46... r = await client.get('https://www.example.org/')47...48>>> r49<Response [200 OK]>47```shell48$ pip install --pre 'httpx[cli]' # The command line client is an optional dependency.49```5051Which now allows us to use HTTPX directly from the command-line...5253<p align="center">54 <img width="700" src="docs/img/httpx-help.png" alt='httpx --help'>55</p>5657Sending a request...5859<p align="center">60 <img width="700" src="docs/img/httpx-request.png" alt='httpx http://httpbin.org/json'>61</p>6263## Features6465HTTPX builds on the well-established usability of `requests`, and gives you:6667* A broadly [requests-compatible API](https://www.python-httpx.org/compatibility/).57* Standard synchronous interface, but with [async support if you need it](https://www.python-httpx.org/async/).68* An integrated command-line client.69* HTTP/1.1 [and HTTP/2 support](https://www.python-httpx.org/http2/).70* Standard synchronous interface, but with [async support if you need it](https://www.python-httpx.org/async/).71* Ability to make requests directly to [WSGI applications](https://www.python-httpx.org/advanced/#calling-into-python-web-apps) or [ASGI applications](https://www.python-httpx.org/async/#calling-into-python-web-apps).72* Strict timeouts everywhere.73* Fully type annotated.74* 100% test coverage.
72 unmodified lines
modified:requirements.txt+1 added-1 removed
1# We're pinning our tooling, because it's an environment we can strictly control.2# On the other hand, we're not pinning package dependencies, because our tests3# needs to pass with the latest version of the packages.4# Reference: https://github.com/encode/httpx/pull/1721#discussion_r6612415885-e .[http2,brotli]5-e .[cli,http2,brotli]67# Documentation8mkdocs==1.2.29mkautodoc==0.1.0
24 unmodified lines
modified:setup.py+8 added
67 unmodified lines
68 "brotli": [69 "brotli; platform_python_implementation == 'CPython'",70 "brotlicffi; platform_python_implementation != 'CPython'"71 ],72 "cli": [73 "click==8.*",74 "rich==10.*",75 "pygments==2.*"76 ]77 },78 entry_points = {79 "console_scripts": "httpx=httpx:main"80 },81 classifiers=[82 "Development Status :: 4 - Beta",83 "Environment :: Web Environment",84 "Intended Audience :: Developers",
14 unmodified lines