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
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
Provenance
- Commit
ee9250d- Tree
6d757f7- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
a761e17
14 files changed+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 Guide2 3-HTTPX aims to be broadly compatible with the `requests` API.3+HTTPX aims to be broadly compatible with the `requests` API, although there are a4+few design differences in places.5 6 This documentation outlines places where the API differs...7 7-## Client instances8-9-The HTTPX equivalent of `requests.Session` is `httpx.Client`.10-11-```python12-session = requests.Session(**kwargs)13-```14-15-is generally equivalent to16-17-```python18-client = httpx.Client(**kwargs)19-```20-21-## Request URLs22-23-Accessing `response.url` will return a `URL` instance, rather than a string.24-25-Use `str(response.url)` if you need a string instance.26-8 ## Redirects9 10 Unlike `requests`, HTTPX does **not follow redirects by default**.11 12 unmodified lines24 ```python25 client = httpx.Client(follow_redirects=True)26 ```27 28+## Client instances29+30+The HTTPX equivalent of `requests.Session` is `httpx.Client`.31+32+```python33+session = requests.Session(**kwargs)34+```35+36+is generally equivalent to37+38+```python39+client = httpx.Client(**kwargs)40+```41+42+## Request URLs43+44+Accessing `response.url` will return a `URL` instance, rather than a string.45+46+Use `str(response.url)` if you need a string instance.47+48 ## Determining the next redirect request49 50 The `requests` library exposes an attribute `response.next`, which can be used to obtain the next redirect request.51 45 unmodified lines97 98 ## Content encoding99 100 HTTPX 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")`.101+For 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.102 101-For 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. 102-103 ## Cookies104 105 If using a client instance, then cookies should always be set on the client rather than on a per-request basis.106 25 unmodified lines132 133 For example:134 135 ```python136-with request.stream("GET", "https://www.example.com") as response:136+with httpx.stream("GET", "https://www.example.com") as response:137 ...138 ```139 140 Within a `stream()` block request data is made available with:23 unmodified lines164 Requests 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.165 166 ## Request body on HTTP methods167 168-The 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.168+The 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.169 170 If you really do need to send request data using these http methods you should use the generic `.request` function instead.171 172-## Checking for 4xx/5xx responses172+```python173+httpx.request(174+ method="DELETE",175+ url="https://www.example.com/",176+ content=b'A request body on a DELETE request.'177+)178+```179 174-We 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 responses181 182+We 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.183+184 ## Request instantiation185 186 There 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 linesmodified:docs/index.md+22 added-17 removed
23 unmodified lines2425262728282930303132333233363435363738394041424344455 unmodified lines515253545155565354555657585960615758596061626364656667686970716667727374757676 unmodified lines23 unmodified linesHTTPX 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.
!!! note HTTPX should currently be considered in beta. This is the documentation for the 1.0 pre-release.
We believe we've got the public API to a stable point now, but would strongly recommend pinning your dependencies to the `0.19.*` release, so that you're able to properly review [API changes between package updates](https://github.com/encode/httpx/blob/master/CHANGELOG.md). 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. See [the CHANGELOG](https://github.com/encode/httpx/blob/version-1.0/CHANGELOG.md) for more details.
A 1.0 release is expected to be issued sometime in 2021.
---
Let's get started...Installing the HTTPX 1.0 pre-release.
```shell$ pip install httpx --pre```
Now, let's get started...
```pycon>>> import httpx>>> r = httpx.get('https://www.example.org/')>>> r5 unmodified lines>>> r.text'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'```
Or, using the async API...Or, using the command-line client.
_Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.8+ with `python -m asyncio` to try this code interactively._
```pycon>>> import httpx>>> async with httpx.AsyncClient() as client:... r = await client.get('https://www.example.org/')...>>> r<Response [200 OK]>```shell# The command line client is an optional dependency.$ pip install --pre 'httpx[cli]'```
Which now allows us to use HTTPX directly from the command-line...

Sending a request...

## Features
HTTPX is a high performance asynchronous HTTP client, that builds on thewell-established usability of `requests`, and gives you:HTTPX builds on the well-established usability of `requests`, and gives you:
* A broadly [requests-compatible API](compatibility.md).* Standard synchronous interface, but with [async support if you need it](async.md).* HTTP/1.1 [and HTTP/2 support](http2.md).76 unmodified linesmodified:docs/quickstart.md+2 added-5 removed
71 unmodified lines72 'UTF-8'73 ```74 75 In some cases the response may not contain an explicit encoding, in which case HTTPX76-will attempt to automatically determine an encoding to use. This defaults to77-UTF-8, but also includes robust fallback behaviour for handling ascii,78-iso-8859-1 and windows 1252 encodings.76+will attempt to automatically determine an encoding to use.77 78 ```pycon79 >>> r.encoding80 None81 >>> r.text82 '<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'83 ```84 87-85 If you need to override the standard behaviour and explicitly set the encoding to86 use, then you can do that too.87 88 ```pycon184 unmodified lines273 >>> r.status_code == httpx.codes.OK274 True275 ```276 280-We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):277+We can raise an exception for any responses which are not a 2xx success code:278 279 ```pycon280 >>> not_found = httpx.get('https://httpbin.org/status/404')281 >>> not_found.status_code200 unmodified linesmodified:httpx/__init__.py+16 added
41 unmodified lines42 from ._transports.mock import MockTransport43 from ._transports.wsgi import WSGITransport44 from ._types import AsyncByteStream, SyncByteStream45 46+try:47+ from ._main import main48+except ImportError: # pragma: nocover49+50+ def main() -> None: # type: ignore51+ import sys52+53+ 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)59+60+61 __all__ = [62 "__description__",63 "__title__",64 "__version__",25 unmodified lines90 "HTTPTransport",91 "InvalidURL",92 "Limits",93 "LocalProtocolError",94+ "main",95 "MockTransport",96 "NetworkError",97 "options",98 "patch",38 unmodified linesmodified: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
1+import json2+import sys3+import typing4+5+import click6+import pygments.lexers7+import pygments.util8+import rich.console9+import rich.progress10+import rich.syntax11+12+from ._client import Client13+from ._exceptions import RequestError14+from ._models import Request, Response15+16+17+def print_help() -> None:18+ console = rich.console.Console()19+20+ 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()28+29+ 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+ )65+66+ table.add_row(67+ "--proxy [cyan]URL",68+ "Send the request via a proxy. Should be the URL giving the proxy address.",69+ )70+71+ 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+ )76+77+ 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+ )82+83+ table.add_row(84+ "--download [cyan]FILE",85+ "Save the response content as a file, rather than displaying it.",86+ )87+88+ 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)91+92+93+def 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: nocover102+103+104+def 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)111+112+113+def 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)121+122+123+def 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)130+131+132+def 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)137+138+139+def print_delimiter() -> None:140+ console = rich.console.Console()141+ syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True)142+ console.print(syntax)143+144+145+def print_redirects(response: Response) -> None:146+ if response.has_redirect_location:147+ response.read()148+ print_response_headers(response)149+ print_response(response)150+151+152+def 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)168+169+170+def 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)174+175+ 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)189+190+191+def 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 None198+199+ try:200+ return json.loads(value)201+ except json.JSONDecodeError: # pragma: nocover202+ raise click.BadParameter("Not valid JSON")203+204+205+def 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 None212+213+ username, password = value214+ if password == "-": # pragma: nocover215+ password = click.prompt("Password", hide_input=True)216+ return (username, password)217+218+219+def 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+ return226+227+ print_help()228+ ctx.exit()229+230+231+@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+)370+def 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"395+396+ 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]401+402+ 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)424+425+ 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)432+433+ except RequestError as exc:434+ console = rich.console.Console()435+ console.print(f"{type(exc).__name__}: {exc}")436+ sys.exit(1)437+438+ sys.exit(0 if response.is_success else 1)modified:tests/conftest.py+13 added
82 unmodified lines83 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)91 92 7 unmodified lines100 )101 await send({"type": "http.response.body", "body": b"Hello, world!"})102 103 104+async 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!"}'})113+114+115 async def slow_response(scope, receive, send):116 await sleep(1.0)117 await send(118 {184 unmodified linesadded:tests/test_main.py+165 added
1+import os2+3+from click.testing import CliRunner4+5+import httpx6+7+8+def splitlines(output):9+ return [line.strip() for line in output.splitlines()]10+11+12+def remove_date_header(lines):13+ return [line for line in lines if not line.startswith("date:")]14+15+16+def 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.output21+22+23+def 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+ ]36+37+38+def 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+ ]53+54+55+def 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+ ]66+67+68+def 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+ ]86+87+88+def 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+ ]101+102+103+def 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+ ]123+124+125+def 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+ ]147+148+149+def 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!"157+158+159+def 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 lines3 All notable changes to this project will be documented in this file.4 5 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).6 7+## 1.0.0.beta08+9+The 1.0 pre-release adds an integrated command-line client, and also includes some10+design changes. The most notable of these is that redirect responses are no longer11+automatically followed, unless specifically requested.12+13+This design decision prioritises a more explicit approach to redirects, in order14+to avoid code that unintentionally issues multiple requests as a result of15+misconfigured URLs.16+17+For example, previously a client configured to send requests to `http://api.github.com/`18+would end up sending every API request twice, as each request would be redirected to `https://api.github.com/`.19+20+If you do want auto-redirect behaviour, you can enable this either by configuring21+the client instance with `Client(follow_redirects=True)`, or on a per-request22+basis, with `.get(..., follow_redirects=True)`.23+24+This change is a classic trade-off between convenience and precision, with no "right"25+answer. See [discussion #1785](https://github.com/encode/httpx/discussions/1785) for more26+context.27+28+The other major design change is an update to the Transport API, which is the low-level29+interface against which requests are sent. Previously this interface used only primitive30+datastructures, like so...31+32+```python33+(status_code, headers, stream, extensions) = transport.handle_request(method, url, headers, stream, extensions)34+try35+ ...36+finally:37+ stream.close()38+```39+40+Now the interface is much simpler...41+42+```python43+response = transport.handle_request(request)44+try45+ ...46+finally:47+ response.close()48+```49+50+### Changed51+52+* 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']`.61+62+### Added63+64+* 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.67+68+### Fixed69+70+* `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)73+74 ## 0.19.0 (19th August, 2021)75 76 ### Added77 801 unmodified linesmodified:README.md+28 added-16 removed
11 unmodified lines12 <img src="https://badge.fury.io/py/httpx.svg" alt="Package version">13 </a>14 </p>15 16-HTTPX 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.16+HTTPX is a fully featured HTTP client library for Python 3. It includes **an integrated17+command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync18+and async APIs**.19 18-**Note**: _HTTPX should be considered in beta. We believe we've got the public API to19-a stable point now, but would strongly recommend pinning your dependencies to the `0.19.*`20-release, 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.*21 22 ---23 24-Let's get started...24+Installing HTTPX.25 26+```shell27+$ pip install httpx --pre28+```29+30+Now, let's get started...31+32 ```pycon33 >>> import httpx34 >>> r = httpx.get('https://www.example.org/')35 >>> r5 unmodified lines41 >>> r.text42 '<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'43 ```44 39-Or, using the async API...45+Or, using the command-line client.46 41-_Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.8+ with `python -m asyncio` to try this code interactively._42-43-```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 ```50 51+Which now allows us to use HTTPX directly from the command-line...52+53+<p align="center">54+ <img width="700" src="docs/img/httpx-help.png" alt='httpx --help'>55+</p>56+57+Sending a request...58+59+<p align="center">60+ <img width="700" src="docs/img/httpx-request.png" alt='httpx http://httpbin.org/json'>61+</p>62+63 ## Features64 65 HTTPX builds on the well-established usability of `requests`, and gives you:66 67 * 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 linesmodified: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]6 7 # Documentation8 mkdocs==1.2.29 mkautodoc==0.1.024 unmodified linesmodified:setup.py+8 added
67 unmodified lines68 "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