Skip to content
Myr

Drop sync (#544)

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

Drop sync client

authored by Tom Christie · committed by GitHub · parent 1c326d5 · Browse files · 52 files+845 added−2405 removed
This commit

State

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

Diff stats

52 files+845 added−2405 removed

  • tests:+442 added−814 removed
  • other:+403 added−1591 removed

52 files+845 added−2405 removed

modified:docs/advanced.md+88 added-57 removed
12 unmodified lines
1314The recommended way to use a `Client` is as a context manager. This will ensure that connections are properly cleaned up when leaving the `with` block:1516```python17>>> with httpx.Client() as client:18... r = client.get('https://example.com')19... 17>>> async with httpx.Client() as client:18... r = await client.get('https://example.com')19...20>>> r21<Response [200 OK]>22```23
1 unmodified line
2526```python27>>> client = httpx.Client()28>>> try:29... r = client.get('https://example.com')29... r = await client.get('https://example.com')30... finally:31... client.close()32... 31... await client.close()32...33>>> r34<Response [200 OK]>35```36
7 unmodified lines
4445```python46>>> url = 'http://httpbin.org/headers'47>>> headers = {'user-agent': 'my-app/0.0.1'}48>>> with httpx.Client(headers=headers) as client:49... r = client.get(url)48>>> async with httpx.Client(headers=headers) as client:49... r = await client.get(url)50...51>>> r.json()['headers']['User-Agent']52'my-app/0.0.1'53```5455!!! note56 When you provide a parameter at both the client and request levels, one of two things can happen:57 5758 - For headers, query parameters and cookies, the values are merged into one.59 - For all other parameters, the request-level value is used.6061Additionally, `Client` constructor accepts some parameters that aren't available at the request level.6263One particularly useful parameter is `base_url`, which allows you to define a base URL to prepend to all outgoing requests:6465```python66>>> with httpx.Client(base_url='http://httpbin.org') as client:67... r = client.get('/headers')68... 66>>> async with httpx.Client(base_url='http://httpbin.org') as client:67... r = await client.get('/headers')68...69>>> r.request.url70URL('http://httpbin.org/headers')71```72
1 unmodified line
7475## Calling into Python Web Apps7677You can configure an `httpx` client to call directly into a Python web78application using either the WSGI or ASGI protocol.78application using either the ASGI protocol.7980This is particularly useful for two main use-cases:8182* Using `httpx` as a client inside test cases.83* Mocking out external services during tests or in dev/staging environments.8485Here's an example of integrating against a Flask application:85Let's take this Starlette application as an example:8687```python88from flask import Flask89import httpx88from starlette.applications import Starlette89from starlette.responses import HTMLResponse90from starlette.routing import Route919292app = Flask(__name__)93async def hello():94 return HTMLResponse("Hello World!")9594@app.route("/")95def hello():96 return "Hello World!"9698with httpx.Client(app=app) as client:99 r = client.get('http://example/')100 assert r.status_code == 200101 assert r.text == "Hello World!"97app = Starlette(routes=[Route("/", hello)])98```99100We can make requests directly against the application, like so:101102```python103>>> import httpx104>>> async with httpx.Client(app=app) as client:105... r = client.get('http://example/')106... assert r.status_code == 200107... assert r.text == "Hello World!"108```109110For some more complex cases you might need to customize the WSGI or ASGI111dispatch. This allows you to:112113* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.108* Mount the WSGI or ASGI application at a subpath by setting `script_name` (WSGI) or `root_path` (ASGI).109* Use a given client address for requests by setting `remote_addr` (WSGI) or `client` (ASGI).114* Mount the WSGI or ASGI application at a subpath by setting `root_path`.115* Use a given client address for requests by setting `client`.116117For example:118119```python120# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".115dispatch = httpx.dispatch.WSGIDispatch(app=app, remote_addr="1.2.3.4")116with httpx.Client(dispatch=dispatch) as client:121dispatch = httpx.dispatch.ASGIDispatch(app=app, remote_addr="1.2.3.4")122async with httpx.Client(dispatch=dispatch) as client:123 ...124```125126## Build Request
1 unmodified line
128You can use `Client.build_request()` to build a request and129make modifications before sending the request.130131```python126>>> with httpx.Client() as client:132>>> async with httpx.Client() as client:133... req = client.build_request("OPTIONS", "https://example.com")134... req.url.full_path = "*" # Build an 'OPTIONS *' request for CORS129... r = client.send(req)135... r = await client.send(req)136...137>>> r138<Response [200 OK]>139```
4 unmodified lines
144145For example:146147```python142with httpx.Client(http_versions=["HTTP/1.1"]) as h11_client:143 h11_response = h11_client.get("https://myserver.com")148async with httpx.Client(http_versions=["HTTP/1.1"]) as h11_client:149 h11_response = await h11_client.get("https://myserver.com")150145with httpx.Client(http_versions=["HTTP/2"]) as h2_client:146 h2_response = h2_client.get("https://myserver.com")151async with httpx.Client(http_versions=["HTTP/2"]) as h2_client:152 h2_response = await h2_client.get("https://myserver.com")153```154155## .netrc Support156
6 unmodified lines
163 you should create a new client or restart the interpreter.164165As default `trust_env` is true. To set false:166```python161>>> httpx.get('https://example.org/', trust_env=False)167>>> await httpx.get('https://example.org/', trust_env=False)168```169170If `NETRC` environment is empty, HTTPX tries to use default files.171(`~/.netrc`, `~/_netrc`)
22 unmodified lines
194```python195import httpx196197192with httpx.Client(uds="/var/run/docker.sock") as client:198async with httpx.Client(uds="/var/run/docker.sock") as client:199 # This request will connect through the socket file.194 resp = client.get("http://localhost/version")200 resp = await client.get("http://localhost/version")201```202203## HTTP Proxying204
5 unmodified lines
210>>> proxies = {211... "http": "http://127.0.0.1:3080",212... "https": "http://127.0.0.1:3081"213... }208>>> with httpx.Client(proxies=proxies) as client:214>>> async with httpx.Client(proxies=proxies) as client:215... ...216```217218Proxies can be configured for a specific scheme and host, all schemes of a host,
6 unmodified lines
225... "all://example.com": "...", # Host226... "http": "...", # Scheme227... "all": "...", # All228... }223>>> with httpx.Client(proxies=proxies) as client:229>>> async with httpx.Client(proxies=proxies) as client:230... ...225... 231...232>>> proxy = "..." # Shortcut for {'all': '...'}227>>> with httpx.Client(proxies=proxy) as client:233>>> async with httpx.Client(proxies=proxy) as client:234... ...235```236237!!! warning
11 unmodified lines
249proxy = httpx.HTTPProxy(250 proxy_url="https://127.0.0.1",251 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY252)247with httpx.Client(proxies=proxy) as client:253async with httpx.Client(proxies=proxy) as client:254 # This request will be tunneled instead of forwarded.249 r = client.get("http://example.com")255 r = await client.get("http://example.com")256```257258!!! note259
23 unmodified lines
283- For a given request:284285```python286# Using top-level API281httpx.get('http://example.com/api/v1/example', timeout=5)287await httpx.get('http://example.com/api/v1/example', timeout=5)288289# Or, with a client:284with httpx.Client() as client:285 client.get("http://example.com/api/v1/example", timeout=5)290async with httpx.Client() as client:291 await client.get("http://example.com/api/v1/example", timeout=5)292```293294- On a client instance, which results in the given `timeout` being used as a default for requests made with this client:295296```python291with httpx.Client(timeout=5) as client:292 client.get('http://example.com/api/v1/example')297async with httpx.Client(timeout=5) as client:298 await client.get('http://example.com/api/v1/example')299```300301Besides, you can pass timeouts in two forms:302
6 unmodified lines
309 read_timeout=10,310 write_timeout=15311)312307resp = httpx.get('http://example.com/api/v1/example', timeout=timeout)313resp = await httpx.get('http://example.com/api/v1/example', timeout=timeout)314```315316### Default timeouts317
6 unmodified lines
324325```python326url = "http://example.com/api/v1/delay/10"327322httpx.get(url, timeout=None) # Times out after 5s328await httpx.get(url, timeout=None) # Times out after 5s329330325with httpx.Client(timeout=None) as client:326 client.get(url) # Does not timeout, returns after 10s331async with httpx.Client(timeout=None) as client:332 await client.get(url) # Does not timeout, returns after 10s333334335timeout = httpx.TimeoutConfig(336 connect_timeout=5,337 read_timeout=None,338 write_timeout=5339)334httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s340await httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s341```342343## Multipart file encoding344
2 unmodified lines
347name of the payloads as keys and a tuple of elements as values.348349```python350>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}345>>> r = httpx.post("https://httpbin.org/post", files=files)351>>> r = await httpx.post("https://httpbin.org/post", files=files)352>>> print(r.text)353{354 ...355 "files": {
15 unmodified lines
371`applicaction/octet-stream`.372373```python374>>> files = {'upload-file': (None, 'text content', 'text/plain')}369>>> r = httpx.post("https://httpbin.org/post", files=files)375>>> r = await httpx.post("https://httpbin.org/post", files=files)376>>> print(r.text)377{378 ...379 "files": {},
18 unmodified lines
398399```python400import httpx401396r = httpx.get("https://example.org", verify="path/to/client.pem")402r = await httpx.get("https://example.org", verify="path/to/client.pem")403```404405### Making HTTPS requests to a local server406
6 unmodified lines
4131. Tell HTTPX to use the certificates stored in `client.pem`:414415```python416>>> import httpx411>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")417>>> r = await httpx.get("https://localhost:8000", verify="/tmp/client.pem")418>>> r419Response <200 OK>420```421422## Support async environments423424### [asyncio](https://docs.python.org/3/library/asyncio.html) (Default)425426By default, `AsyncClient` uses `asyncio` to perform asynchronous operations and I/O calls.427428### [trio](https://github.com/python-trio/trio)429430To make asynchronous requests in `trio` programs, pass a `TrioBackend` to the `AsyncClient`:431432```python433import trio434import httpx435from httpx.concurrency.trio import TrioBackend436437async def main():438 async with httpx.AsyncClient(backend=TrioBackend()) as client:439 ...440441trio.run(main)442```443444!!! important445 `trio` must be installed to import and use the `TrioBackend`.
modified:docs/api.md+2 added-2 removed
deleted:docs/async.md-142 removed
1# Async Client23HTTPX offers a standard synchronous API by default, but also gives you4the option of an async client if you need it.56Async is a concurrency model that is far more efficient than multi-threading,7and can provide significant performance benefits and enable the use of8long-lived network connections such as WebSockets.910If you're working with an async web framework then you'll also want to use an11async client for sending outgoing HTTP requests.1213## Making Async requests1415To make asynchronous requests, you'll need an `AsyncClient`.1617```python18>>> async with httpx.AsyncClient() as client:19>>> r = await client.get('https://www.example.com/')20>>> r21<Response [200 OK]>22```2324!!! tip25 Use [IPython](https://ipython.readthedocs.io/en/stable/) to try this code interactively, as it supports executing `async`/`await` expressions in the console.2627!!! note28 The `async with` syntax ensures that all active connections are closed on exit.2930 It is safe to access response content (e.g. `r.text`) both inside and outside the `async with` block, unless you are using response streaming. In that case, you should `.read()`, `.stream()`, or `.close()` the response *inside* the `async with` block.3132## API Differences3334If you're using streaming responses then there are a few bits of API that35use async methods:3637```python38>>> async with httpx.AsyncClient() as client:39>>> r = await client.get('https://www.example.com/', stream=True)40>>> async for chunk in r.stream():41>>> ...42```4344The async response methods are:4546* `.read()`47* `.stream()`48* `.raw()`49* `.close()`5051If you're making [parallel requests](parallel.md), then you'll also need to use an async API:5253```python54>>> async with httpx.AsyncClient() as client:55>>> async with client.parallel() as parallel:56>>> pending_one = parallel.get('https://example.com/1')57>>> pending_two = parallel.get('https://example.com/2')58>>> response_one = await pending_one.get_response()59>>> response_two = await pending_two.get_response()60```6162The async parallel methods are:6364* `.parallel()` *Used as an "async with" context manager.*65* `.get_response()`66* `.next_response()`6768## Supported async libraries6970You can use `AsyncClient` with any of the following async libraries.7172!!! tip73 You will typically be using `AsyncClient` in async programs that run on `asyncio`. If that's the case, or if you're not sure what this is all about, you can safely ignore this section.7475### [asyncio](https://docs.python.org/3/library/asyncio.html) (Default)7677By default, `AsyncClient` uses `asyncio` to perform asynchronous operations and I/O calls.7879```python80import asyncio81import httpx8283async def main():84 async with httpx.AsyncClient() as client:85 ...8687asyncio.run(main())88```8990### [trio](https://github.com/python-trio/trio)9192To make asynchronous requests in `trio` programs, pass a `TrioBackend` to the `AsyncClient`:9394```python95import trio96import httpx97from httpx.concurrency.trio import TrioBackend9899async def main():100 async with httpx.AsyncClient(backend=TrioBackend()) as client:101 ...102103trio.run(main)104```105106!!! important107 `trio` must be installed to import and use the `TrioBackend`.108109## FAQ110111### When should I use an `AsyncClient`?112113You should use an `AsyncClient` whenever you are inside an *async environment*.114115In particular, using `httpx.get()` or `httpx.Client()` in an async environment is **not** supported. There are several technical reasons to this, but the rationale is that you shouldn't be doing blocking-style network calls in the context of an event loop (for more discussion, see [#179](https://github.com/encode/httpx/issues/179)).116117For example, this won't work:118119```python120import asyncio121import httpx122123async def main():124 r = httpx.get("https://example.org")125126asyncio.run(main())127```128129Instead, you should use an `AsyncClient`:130131```python132import asyncio133import httpx134135async def main():136 async with httpx.AsyncClient() as client:137 r = await client.get("https://example.org")138139asyncio.run(main())140```141142If you *need* to make synchronous requests, or otherwise run into issues related to sync usage, you should probably consider using a regular threaded client such as [Requests](https://github.com/psf/requests) instead.
modified:docs/compatibility.md+3 added-3 removed
modified:docs/index.md+22 added-13 removed
22 unmodified lines
2324<em>A next-generation HTTP client for Python.</em>25</div>2627!!! warning28 This project should be considered as an "alpha" release. It is substantially29 API complete, but there are still some areas that need more work.27HTTPX is an asynchronous HTTP client, that supports HTTP/2 and HTTP/1.1.2829It can be used in high-performance async web frameworks, using either asyncio30or trio, and is able to support making large numbers of requests concurrently.3132!!! note33 The 0.8 release switched HTTPX into focusing exclusively on the async34 client. It is possible that we'll look at re-introducing a sync API at a35 later date.3637---3839Let's get started...4041!!! note42 The standard Python REPL does not allow top-level async statements.4344 To run async examples directly you'll probably want to either use `ipython`,45 or use Python 3.8 with `python -m asyncio`.4647```python48>>> import httpx37>>> r = httpx.get('https://www.example.org/')49>>> r = await httpx.get('https://www.example.org/')50>>> r51<Response [200 OK]>52>>> r.status_code53200
6 unmodified lines
60```6162## Features6364HTTPX is a high performance asynchronous HTTP client, that builds on the52HTTPX builds on the well-established usability of `requests`, and gives you:65well-established usability of `requests`, and gives you:6654* A requests-compatible API.67* A broadly requests-compatible API.68* HTTP/2 and HTTP/1.1 support.56* Support for [issuing HTTP requests in parallel](parallel.md). *(Coming soon)*57* Standard synchronous interface, but [with `async`/`await` support if you need it](async.md).58* Ability to [make requests directly to WSGI or ASGI applications](advanced.md#calling-into-python-web-apps).69* Ability to [make requests directly to ASGI applications](advanced.md#calling-into-python-web-apps).70* Strict timeouts everywhere.71* Fully type annotated.72* 100% test coverage.73
8 unmodified lines
82* Automatic Decompression83* Automatic Content Decoding84* Unicode Response Bodies85* Multipart File Uploads75* HTTP(S) Proxy Support *(TODO)*86* HTTP(S) Proxy Support87* Connection Timeouts88* Streaming Downloads89* .netrc Support90* Chunked Requests
1 unmodified line
92## Documentation9394For a run-through of all the basics, head over to the [QuickStart](quickstart.md).9585For more advanced topics, see the [Advanced Usage](advanced.md) section, or86the specific topics on making [Parallel Requests](parallel.md) or using the87[Async Client](async.md).96For more advanced topics, see the [Advanced Usage](advanced.md) section.9798The [Developer Interface](api.md) provides a comprehensive API reference.99100## Dependencies
25 unmodified lines
deleted:docs/parallel.md-70 removed
1# Parallel Requests23!!! warning4 This page documents some proposed functionality that is not yet released.5 See [pull request #52](https://github.com/encode/httpx/pull/52) for the6 first-pass of an implementation.78HTTPX allows you to make HTTP requests in parallel in a highly efficient way,9using async under the hood, while still presenting a standard threaded interface.1011This has the huge benefit of allowing you to efficiently make parallel HTTP12requests without having to switch out to using async all the way through.1314## Making Parallel Requests1516Let's make two outgoing HTTP requests in parallel:1718```python19>>> with httpx.parallel() as parallel:20>>> pending_one = parallel.get('https://example.com/1')21>>> pending_two = parallel.get('https://example.com/2')22>>> response_one = pending_one.get_response()23>>> response_two = pending_two.get_response()24```2526If we're making lots of outgoing requests, we might not want to deal with the27responses sequentially, but rather deal with each response that comes back28as soon as it's available:2930```python31>>> with httpx.parallel() as parallel:32>>> for counter in range(1, 10):33>>> parallel.get(f'https://example.com/{counter}')34>>> while parallel.has_pending_responses:35>>> r = parallel.next_response()36```3738## Exceptions and Cancellations3940The style of using `parallel` blocks ensures that you'll always have a well-defined exception and cancellation behaviors. Request exceptions are only ever41raised when calling either `get_response` or `next_response` and any pending42requests are canceled on exiting the block.4344## Parallel requests with a Client4546You can also call `parallel()` from a client instance, which allows you to47control the authentication or dispatch behavior for all requests within the48block.4950```python51>>> with httpx.Client() as client:52... with client.parallel() as parallel:53... ...54```5556## Async parallel requests5758If you're working within an async framework, then you'll want to use a fully59async API for making requests.6061```python62>>> async with httpx.AsyncClient() as client:63... async with client.parallel() as parallel:64... pending_one = await parallel.get('https://example.com/1')65... pending_two = await parallel.get('https://example.com/2')66... response_one = await pending_one.get_response()67... response_two = await pending_two.get_response()68```6970See [the Async Client documentation](async.md) for more details.
modified:docs/quickstart.md+31 added-30 removed
1# QuickStart23!!! note4 This page closely follows the layout of the `requests` QuickStart documentation.5 The `httpx` library is designed to be API compatible with `requests` wherever6 possible.4 The standard Python REPL does not allow top-level async statements.56 To run async examples directly you'll probably want to either use `ipython`,7 or use Python 3.8 with `python -m asyncio`.89First, start by importing HTTPX:1011```python12>>> import httpx
1 unmodified line
1415Now, let’s try to get a webpage.1617```python17>>> r = httpx.get('https://httpbin.org/get')18>>> r = await httpx.get('https://httpbin.org/get')19>>> r20<Response [200 OK]>21```2223Similarly, to make an HTTP POST request:2425```python25>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})26>>> r = await httpx.post('https://httpbin.org/post', data={'key': 'value'})27```2829The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:3031```python31>>> r = httpx.put('https://httpbin.org/put', data={'key': 'value'})32>>> r = httpx.delete('https://httpbin.org/delete')33>>> r = httpx.head('https://httpbin.org/get')34>>> r = httpx.options('https://httpbin.org/get')32>>> r = await httpx.put('https://httpbin.org/put', data={'key': 'value'})33>>> r = await httpx.delete('https://httpbin.org/delete')34>>> r = await httpx.head('https://httpbin.org/get')35>>> r = await httpx.options('https://httpbin.org/get')36```3738## Passing Parameters in URLs3940To include URL query parameters in the request, use the `params` keyword:4142```python43>>> params = {'key1': 'value1', 'key2': 'value2'}43>>> r = httpx.get('https://httpbin.org/get', params=params)44>>> r = await httpx.get('https://httpbin.org/get', params=params)45```4647To see how the values get encoding into the URL string, we can inspect the48resulting URL that was used to make the request:
6 unmodified lines
55You can also pass a list of items as a value:5657```python58>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}58>>> r = httpx.get('https://httpbin.org/get', params=params)59>>> r = await httpx.get('https://httpbin.org/get', params=params)60>>> r.url61URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')62```63
1 unmodified line
6566HTTPX will automatically handle decoding the response content into Unicode text.6768```python68>>> r = httpx.get('https://www.example.org/')69>>> r = await httpx.get('https://www.example.org/')70>>> r.text71'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'72```73
36 unmodified lines
110111Often Web API responses will be encoded as JSON.112113```python113>>> r = httpx.get('https://api.github.com/events')114>>> r = await httpx.get('https://api.github.com/events')115>>> r.json()116[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]117```118
3 unmodified lines
122123```python124>>> url = 'http://httpbin.org/headers'125>>> headers = {'user-agent': 'my-app/0.0.1'}125>>> r = httpx.get(url, headers=headers)126>>> r = await httpx.get(url, headers=headers)127```128129## Sending Form Encoded Data130
2 unmodified lines
133which is used for HTML forms.134135```python136>>> data = {'key1': 'value1', 'key2': 'value2'}136>>> r = httpx.post("https://httpbin.org/post", data=data)137>>> r = await httpx.post("https://httpbin.org/post", data=data)138>>> print(r.text)139{140 ...141 "form": {
7 unmodified lines
149Form encoded data can also include multiple values form a given key.150151```python152>>> data = {'key1': ['value1', 'value2']}152>>> r = httpx.post("https://httpbin.org/post", data=data)153>>> r = await httpx.post("https://httpbin.org/post", data=data)154>>> print(r.text)155{156 ...157 "form": {
11 unmodified lines
169You can also upload files, using HTTP multipart encoding:170171```python172>>> files = {'upload-file': open('report.xls', 'rb')}172>>> r = httpx.post("https://httpbin.org/post", files=files)173>>> r = await httpx.post("https://httpbin.org/post", files=files)174>>> print(r.text)175{176 ...177 "files": {
7 unmodified lines
185of items for the file value:186187```python188>>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}188>>> r = httpx.post("https://httpbin.org/post", files=files)189>>> r = await httpx.post("https://httpbin.org/post", files=files)190>>> print(r.text)191{192 ...193 "files": {
9 unmodified lines
203For more complicated data structures you'll often want to use JSON encoding instead.204205```python206>>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}206>>> r = httpx.post("https://httpbin.org/post", json=data)207>>> r = await httpx.post("https://httpbin.org/post", json=data)208>>> print(r.text)209{210 ...211 "json": {
21 unmodified lines
233234We can inspect the HTTP status code of the response:235236```python236>>> r = httpx.get('https://httpbin.org/get')237>>> r = await httpx.get('https://httpbin.org/get')238>>> r.status_code239200240```241
6 unmodified lines
248249We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):250251```python251>>> not_found = httpx.get('https://httpbin.org/status/404')252>>> not_found = await httpx.get('https://httpbin.org/status/404')253>>> not_found.status_code254404255>>> not_found.raise_for_status()256Traceback (most recent call last):
44 unmodified lines
301302Any cookies that are set on the response can be easily accessed:303304```python304>>> r = httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)305>>> r = await httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)306>>> r.cookies['chocolate']307'chip'308```309310To include cookies in an outgoing request, use the `cookies` parameter:311312```python313>>> cookies = {"peanut": "butter"}313>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)314>>> r = await httpx.get('http://httpbin.org/cookies', cookies=cookies)315>>> r.json()316{'cookies': {'peanut': 'butter'}}317```318
3 unmodified lines
322```python323>>> cookies = httpx.Cookies()324>>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')325>>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')325>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)326>>> r = await httpx.get('http://httpbin.org/cookies', cookies=cookies)327>>> r.json()328{'cookies': {'cookie_on_domain': 'hello, there!'}}329```330
7 unmodified lines
338339For example, GitHub redirects all HTTP requests to HTTPS.340341```python341>>> r = httpx.get('http://github.com/')342>>> r = await httpx.get('http://github.com/')343>>> r.url344URL('https://github.com/')345>>> r.status_code346200
3 unmodified lines
350351You can modify the default redirection handling with the allow_redirects parameter:352353```python353>>> r = httpx.get('http://github.com/', allow_redirects=False)354>>> r = await httpx.get('http://github.com/', allow_redirects=False)355>>> r.status_code356301357>>> r.history358[]
1 unmodified line
360361If you’re making a `HEAD` request, you can use this to enable redirection:362363```python363>>> r = httpx.head('http://github.com/', allow_redirects=True)364>>> r = await httpx.head('http://github.com/', allow_redirects=True)365>>> r.url366'https://github.com/'367>>> r.history368[<Response [301 Moved Permanently]>]
8 unmodified lines
377The default timeout for network inactivity is five seconds. You can modify the378value to be more or less strict:379380```python380>>> httpx.get('https://github.com/', timeout=0.001)381>>> await httpx.get('https://github.com/', timeout=0.001)382```383384For advanced timeout management, see [Timeout fine-tuning](https://www.encode.io/httpx/advanced/#timeout-fine-tuning).385
5 unmodified lines
391plaintext `str` or `bytes` objects as the `auth` argument to the request392functions:393394```python394>>> httpx.get("https://example.com", auth=("my_user", "password123"))395>>> await httpx.get("https://example.com", auth=("my_user", "password123"))396```397398To provide credentials for Digest authentication you'll need to instantiate399a `DigestAuth` object with the plaintext username and password as arguments.
1 unmodified line
401as above:402403```python404>>> auth = httpx.DigestAuth("my_user", "password123")404>>> httpx.get("https://example.com", auth=auth)405>>> await httpx.get("https://example.com", auth=auth)406<Response [200 OK]>407```
modified:httpx/dispatch/__init__.py+1 added-2 removed
1 unmodified line
2Dispatch classes handle the raw network connections and the implementation3details of making the HTTP request and receiving the response.4"""5from .asgi import ASGIDispatch6from .wsgi import WSGIDispatch68__all__ = ["ASGIDispatch", "WSGIDispatch"]7__all__ = ["ASGIDispatch"]
modified:httpx/dispatch/asgi.py+6 added-6 removed
1 unmodified line
23from ..concurrency.asyncio import AsyncioBackend4from ..concurrency.base import ConcurrencyBackend5from ..config import CertTypes, TimeoutTypes, VerifyTypes6from ..models import AsyncRequest, AsyncResponse6from ..models import Request, Response7from ..utils import MessageLoggerASGIMiddleware, get_logger8from .base import AsyncDispatcher8from .base import Dispatcher910logger = get_logger(__name__)111213class ASGIDispatch(AsyncDispatcher):13class ASGIDispatch(Dispatcher):14 """15 A custom dispatcher that handles sending requests directly to an ASGI app.1617 The simplest way to use this functionality is to use the `app` argument.
43 unmodified lines
61 self.backend = AsyncioBackend() if backend is None else backend6263 async def send(64 self,65 request: AsyncRequest,65 request: Request,66 verify: VerifyTypes = None,67 cert: CertTypes = None,68 timeout: TimeoutTypes = None,69 ) -> AsyncResponse:69 ) -> Response:7071 scope = {72 "type": "http",73 "asgi": {"version": "3.0"},
71 unmodified lines
145 await background.close(app_exc)146 if app_exc is not None and self.raise_app_exceptions:147 raise app_exc148149 return AsyncResponse(149 return Response(150 status_code=status_code,151 http_version="HTTP/1.1",152 headers=headers,153 content=response_body.iterate(),
45 unmodified lines
modified:httpx/dispatch/base.py+8 added-59 removed
1 unmodified line
2from types import TracebackType34from ..config import CertTypes, TimeoutTypes, VerifyTypes5from ..models import (6 AsyncRequest,7 AsyncRequestData,8 AsyncResponse,6 HeaderTypes,7 QueryParamTypes,8 Request,9 RequestData,
1 unmodified line
11 URLTypes,12)131418class AsyncDispatcher:15class Dispatcher:16 """20 Base class for async dispatcher classes, that handle sending the request.17 Base class for dispatcher classes, that handle sending the request.1819 Stubs out the interface, as well as providing a `.request()` convenience20 implementation, to make it easy to use or test stand-alone dispatchers,21 without requiring a complete `Client` instance.
3 unmodified lines
25 self,26 method: str,27 url: URLTypes,28 *,32 data: AsyncRequestData = b"",33 params: QueryParamTypes = None,34 headers: HeaderTypes = None,35 verify: VerifyTypes = None,36 cert: CertTypes = None,37 timeout: TimeoutTypes = None,38 ) -> AsyncResponse:39 request = AsyncRequest(method, url, data=data, params=params, headers=headers)40 return await self.send(request, verify=verify, cert=cert, timeout=timeout)4142 async def send(43 self,44 request: AsyncRequest,45 verify: VerifyTypes = None,46 cert: CertTypes = None,47 timeout: TimeoutTypes = None,48 ) -> AsyncResponse:49 raise NotImplementedError() # pragma: nocover5051 async def close(self) -> None:52 pass # pragma: nocover5354 async def __aenter__(self) -> "AsyncDispatcher":55 return self5657 async def __aexit__(58 self,59 exc_type: typing.Type[BaseException] = None,60 exc_value: BaseException = None,61 traceback: TracebackType = None,62 ) -> None:63 await self.close()646566class Dispatcher:67 """68 Base class for synchronous dispatcher classes, that handle sending the request.6970 Stubs out the interface, as well as providing a `.request()` convenience71 implementation, to make it easy to use or test stand-alone dispatchers,72 without requiring a complete `Client` instance.73 """7475 def request(76 self,77 method: str,78 url: URLTypes,79 *,29 data: RequestData = b"",30 params: QueryParamTypes = None,31 headers: HeaderTypes = None,32 verify: VerifyTypes = None,33 cert: CertTypes = None,34 timeout: TimeoutTypes = None,35 ) -> Response:36 request = Request(method, url, data=data, params=params, headers=headers)88 return self.send(request, verify=verify, cert=cert, timeout=timeout)37 return await self.send(request, verify=verify, cert=cert, timeout=timeout)3890 def send(39 async def send(40 self,41 request: Request,42 verify: VerifyTypes = None,43 cert: CertTypes = None,44 timeout: TimeoutTypes = None,45 ) -> Response:46 raise NotImplementedError() # pragma: nocover4799 def close(self) -> None:48 async def close(self) -> None:49 pass # pragma: nocover50102 def __enter__(self) -> "Dispatcher":51 async def __aenter__(self) -> "Dispatcher":52 return self53105 def __exit__(54 async def __aexit__(55 self,56 exc_type: typing.Type[BaseException] = None,57 exc_value: BaseException = None,58 traceback: TracebackType = None,59 ) -> None:111 self.close()60 await self.close()
modified:httpx/dispatch/connection_pool.py+5 added-5 removed
9 unmodified lines
10 PoolLimits,11 TimeoutTypes,12 VerifyTypes,13)14from ..models import AsyncRequest, AsyncResponse, Origin14from ..models import Origin, Request, Response15from ..utils import get_logger16from .base import AsyncDispatcher16from .base import Dispatcher17from .connection import HTTPConnection1819CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]20
56 unmodified lines
77 def __len__(self) -> int:78 return len(self.all)798081class ConnectionPool(AsyncDispatcher):81class ConnectionPool(Dispatcher):82 def __init__(83 self,84 *,85 verify: VerifyTypes = True,
25 unmodified lines
111 return len(self.keepalive_connections) + len(self.active_connections)112113 async def send(114 self,115 request: AsyncRequest,115 request: Request,116 verify: VerifyTypes = None,117 cert: CertTypes = None,118 timeout: TimeoutTypes = None,119 ) -> AsyncResponse:119 ) -> Response:120 connection = await self.acquire_connection(origin=request.url.origin)121 try:122 response = await connection.send(123 request, verify=verify, cert=cert, timeout=timeout
66 unmodified lines
modified:httpx/dispatch/connection.py+5 added-5 removed
12 unmodified lines
13 TimeoutConfig,14 TimeoutTypes,15 VerifyTypes,16)17from ..models import AsyncRequest, AsyncResponse, Origin17from ..models import Origin, Request, Response18from ..utils import get_logger19from .base import AsyncDispatcher19from .base import Dispatcher20from .http2 import HTTP2Connection21from .http11 import HTTP11Connection2223# Callback signature: async def callback(conn: HTTPConnection) -> None
2 unmodified lines
2627logger = get_logger(__name__)282930class HTTPConnection(AsyncDispatcher):30class HTTPConnection(Dispatcher):31 def __init__(32 self,33 origin: typing.Union[str, Origin],34 verify: VerifyTypes = True,
16 unmodified lines
51 self.h2_connection = None # type: typing.Optional[HTTP2Connection]5253 async def send(54 self,55 request: AsyncRequest,55 request: Request,56 verify: VerifyTypes = None,57 cert: CertTypes = None,58 timeout: TimeoutTypes = None,59 ) -> AsyncResponse:59 ) -> Response:60 if self.h11_connection is None and self.h2_connection is None:61 await self.connect(verify=verify, cert=cert, timeout=timeout)6263 if self.h2_connection is not None:
91 unmodified lines
modified:httpx/dispatch/http11.py+4 added-6 removed
3 unmodified lines
45from ..concurrency.base import BaseSocketStream, ConcurrencyBackend, TimeoutFlag6from ..config import TimeoutConfig, TimeoutTypes7from ..exceptions import ConnectionClosed, ProtocolError8from ..models import AsyncRequest, AsyncResponse8from ..models import Request, Response9from ..utils import get_logger1011H11Event = typing.Union[12 h11.Request,
28 unmodified lines
41 self.on_release = on_release42 self.h11_state = h11.Connection(our_role=h11.CLIENT)43 self.timeout_flag = TimeoutFlag()4445 async def send(46 self, request: AsyncRequest, timeout: TimeoutTypes = None47 ) -> AsyncResponse:45 async def send(self, request: Request, timeout: TimeoutTypes = None) -> Response:46 timeout = None if timeout is None else TimeoutConfig(timeout)4748 await self._send_request(request, timeout)49
1 unmodified line
51 async with self.backend.background_manager(task, *args):52 http_version, status_code, headers = await self._receive_response(timeout)53 content = self._receive_response_data(timeout)5457 return AsyncResponse(55 return Response(56 status_code=status_code,57 http_version=http_version,58 headers=headers,59 content=content,
11 unmodified lines
71 pass72 await self.stream.close()7374 async def _send_request(77 self, request: AsyncRequest, timeout: TimeoutConfig = None75 self, request: Request, timeout: TimeoutConfig = None76 ) -> None:77 """78 Send the request method, URL, and headers to the network.79 """
138 unmodified lines
modified:httpx/dispatch/http2.py+4 added-6 removed
11 unmodified lines
12 TimeoutFlag,13)14from ..config import TimeoutConfig, TimeoutTypes15from ..exceptions import ProtocolError16from ..models import AsyncRequest, AsyncResponse16from ..models import Request, Response17from ..utils import get_logger1819logger = get_logger(__name__)20
15 unmodified lines
36 self.timeout_flags = {} # type: typing.Dict[int, TimeoutFlag]37 self.initialized = False38 self.window_update_received = {} # type: typing.Dict[int, BaseEvent]3940 async def send(41 self, request: AsyncRequest, timeout: TimeoutTypes = None42 ) -> AsyncResponse:40 async def send(self, request: Request, timeout: TimeoutTypes = None) -> Response:41 timeout = None if timeout is None else TimeoutConfig(timeout)4243 # Start sending the request.44 if not self.initialized:
10 unmodified lines
55 status_code, headers = await self.receive_response(stream_id, timeout)56 content = self.body_iter(stream_id, timeout)57 on_close = functools.partial(self.response_closed, stream_id=stream_id)5861 return AsyncResponse(59 return Response(60 status_code=status_code,61 http_version="HTTP/2",62 headers=headers,63 content=content,
32 unmodified lines
96 self.stream.write_no_block(data_to_send)97 self.initialized = True9899 async def send_headers(102 self, request: AsyncRequest, timeout: TimeoutConfig = None100 self, request: Request, timeout: TimeoutConfig = None101 ) -> int:102 stream_id = self.h2_state.get_next_available_stream_id()103 headers = [104 (b":method", request.method.encode("ascii")),
150 unmodified lines
modified:httpx/dispatch/proxy_http.py+4 added-12 removed
13 unmodified lines
14 VerifyTypes,15)16from ..exceptions import ProxyError17from ..middleware.basic_auth import build_basic_auth_header18from ..models import (19 URL,20 AsyncRequest,21 AsyncResponse,22 Headers,23 HeaderTypes,24 Origin,25 URLTypes,26)18from ..models import URL, Headers, HeaderTypes, Origin, Request, Response, URLTypes19from ..utils import get_logger20from .connection import HTTPConnection21from .connection_pool import ConnectionPool22from .http2 import HTTP2Connection
90 unmodified lines
113 async def request_tunnel_proxy_connection(self, origin: Origin) -> HTTPConnection:114 """Creates an HTTPConnection by setting up a TCP tunnel"""115 proxy_headers = self.proxy_headers.copy()116 proxy_headers.setdefault("Accept", "*/*")125 proxy_request = AsyncRequest(117 proxy_request = Request(118 method="CONNECT", url=self.proxy_url.copy_with(), headers=proxy_headers119 )120 proxy_request.url.full_path = f"{origin.host}:{origin.port}"121
94 unmodified lines
216 ) or self.proxy_mode == HTTPProxyMode.FORWARD_ONLY217218 async def send(219 self,228 request: AsyncRequest,220 request: Request,221 verify: VerifyTypes = None,222 cert: CertTypes = None,223 timeout: TimeoutTypes = None,232 ) -> AsyncResponse:224 ) -> Response:225226 if self.should_forward_origin(request.url.origin):227 # Change the request to have the target URL228 # as its full_path and switch the proxy URL
17 unmodified lines
deleted:httpx/dispatch/threaded.py-97 removed
1from ..concurrency.base import ConcurrencyBackend2from ..config import CertTypes, TimeoutTypes, VerifyTypes3from ..models import (4 AsyncRequest,5 AsyncRequestData,6 AsyncResponse,7 AsyncResponseContent,8 Request,9 RequestData,10 Response,11 ResponseContent,12)13from .base import AsyncDispatcher, Dispatcher141516class ThreadedDispatcher(AsyncDispatcher):17 """18 The ThreadedDispatcher class is used to mediate between the Client19 (which always uses async under the hood), and a synchronous `Dispatch`20 class.21 """2223 def __init__(self, dispatch: Dispatcher, backend: ConcurrencyBackend) -> None:24 self.sync_dispatcher = dispatch25 self.backend = backend2627 async def send(28 self,29 request: AsyncRequest,30 verify: VerifyTypes = None,31 cert: CertTypes = None,32 timeout: TimeoutTypes = None,33 ) -> AsyncResponse:34 concurrency_backend = self.backend3536 data = getattr(request, "content", getattr(request, "content_aiter", None))37 sync_data = self._sync_request_data(data)3839 sync_request = Request(40 method=request.method,41 url=request.url,42 headers=request.headers,43 data=sync_data,44 )4546 func = self.sync_dispatcher.send47 kwargs = {48 "request": sync_request,49 "verify": verify,50 "cert": cert,51 "timeout": timeout,52 }53 sync_response = await self.backend.run_in_threadpool(func, **kwargs)54 assert isinstance(sync_response, Response)5556 content = getattr(57 sync_response, "_raw_content", getattr(sync_response, "_raw_stream", None)58 )5960 async_content = self._async_response_content(content)6162 async def async_on_close() -> None:63 nonlocal concurrency_backend, sync_response64 await concurrency_backend.run_in_threadpool(sync_response.close)6566 return AsyncResponse(67 status_code=sync_response.status_code,68 http_version=sync_response.http_version,69 headers=sync_response.headers,70 content=async_content,71 on_close=async_on_close,72 request=request,73 history=sync_response.history,74 )7576 async def close(self) -> None:77 """78 The `.close()` method runs the `Dispatcher.close()` within a threadpool,79 so as not to block the async event loop.80 """81 func = self.sync_dispatcher.close82 await self.backend.run_in_threadpool(func)8384 def _async_response_content(self, content: ResponseContent) -> AsyncResponseContent:85 if isinstance(content, bytes):86 return content8788 # Coerce an async iterator into an iterator, with each item in the89 # iteration run within the event loop.90 assert hasattr(content, "__iter__")91 return self.backend.iterate_in_threadpool(content)9293 def _sync_request_data(self, data: AsyncRequestData) -> RequestData:94 if isinstance(data, bytes):95 return data9697 return self.backend.iterate(data)
deleted:httpx/dispatch/wsgi.py-164 removed
1import io2import typing34from ..config import CertTypes, TimeoutTypes, VerifyTypes5from ..models import Request, Response6from .base import Dispatcher789class WSGIDispatch(Dispatcher):10 """11 A custom dispatcher that handles sending requests directly to an ASGI app.1213 The simplest way to use this functionality is to use the `app`argument.14 This will automatically infer if 'app' is a WSGI or an ASGI application,15 and will setup an appropriate dispatch class:1617 ```18 client = httpx.Client(app=app)19 ```2021 Alternatively, you can setup the dispatch instance explicitly.22 This allows you to include any additional configuration arguments specific23 to the WSGIDispatch class:2425 ```26 dispatch = httpx.WSGIDispatch(27 app=app,28 script_name="/submount",29 remote_addr="1.2.3.4"30 )31 client = httpx.Client(dispatch=dispatch)323334 Arguments:3536 * `app` - The ASGI application.37 * `raise_app_exceptions` - Boolean indicating if exceptions in the application38 should be raised. Default to `True`. Can be set to `False` for use cases39 such as testing the content of a client 500 response.40 * `script_name` - The root path on which the ASGI application should be mounted.41 * `remote_addr` - A string indicating the client IP of incoming requests.42 ```43 """4445 def __init__(46 self,47 app: typing.Callable,48 raise_app_exceptions: bool = True,49 script_name: str = "",50 remote_addr: str = "127.0.0.1",51 ) -> None:52 self.app = app53 self.raise_app_exceptions = raise_app_exceptions54 self.script_name = script_name55 self.remote_addr = remote_addr5657 def send(58 self,59 request: Request,60 verify: VerifyTypes = None,61 cert: CertTypes = None,62 timeout: TimeoutTypes = None,63 ) -> Response:64 environ = {65 "wsgi.version": (1, 0),66 "wsgi.url_scheme": request.url.scheme,67 "wsgi.input": BodyStream(request.stream()),68 "wsgi.errors": io.BytesIO(),69 "wsgi.multithread": True,70 "wsgi.multiprocess": False,71 "wsgi.run_once": False,72 "REQUEST_METHOD": request.method,73 "SCRIPT_NAME": self.script_name,74 "PATH_INFO": request.url.path,75 "QUERY_STRING": request.url.query,76 "SERVER_NAME": request.url.host,77 "SERVER_PORT": str(request.url.port),78 "REMOTE_ADDR": self.remote_addr,79 }80 for key, value in request.headers.items():81 key = key.upper().replace("-", "_")82 if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):83 key = "HTTP_" + key84 environ[key] = value8586 seen_status = None87 seen_response_headers = None88 seen_exc_info = None8990 def start_response(91 status: str, response_headers: list, exc_info: typing.Any = None92 ) -> None:93 nonlocal seen_status, seen_response_headers, seen_exc_info94 seen_status = status95 seen_response_headers = response_headers96 seen_exc_info = exc_info9798 result = self.app(environ, start_response)99100 assert seen_status is not None101 assert seen_response_headers is not None102 if seen_exc_info and self.raise_app_exceptions:103 raise seen_exc_info[1]104105 return Response(106 status_code=int(seen_status.split()[0]),107 http_version="HTTP/1.1",108 headers=seen_response_headers,109 content=(chunk for chunk in result),110 on_close=getattr(result, "close", None),111 )112113114class BodyStream(io.RawIOBase):115 def __init__(self, iterator: typing.Iterator[bytes]) -> None:116 self._iterator = iterator117 self._buffer = b""118 self._closed = False119120 def read(self, size: int = -1) -> bytes:121 if self._closed:122 return b""123124 if size == -1:125 return self.readall()126127 try:128 while len(self._buffer) < size:129 self._buffer += next(self._iterator)130 except StopIteration:131 self._closed = True132 return self._buffer133134 output = self._buffer[:size]135 self._buffer = self._buffer[size:]136 return output137138 def readall(self) -> bytes:139 if self._closed:140 raise OSError("Stream closed") # pragma: nocover141142 for chunk in self._iterator:143 self._buffer += chunk144145 self._closed = True146 return self._buffer147148 def readinto(self, b: bytearray) -> typing.Optional[int]: # pragma: nocover149 output = self.read(len(b))150 count = len(output)151 b[:count] = output152 return count153154 def write(self, b: bytes) -> int:155 raise OSError("Operation not supported") # pragma: nocover156157 def fileno(self) -> int:158 raise OSError("Operation not supported") # pragma: nocover159160 def seek(self, offset: int, whence: int = 0) -> int:161 raise OSError("Operation not supported") # pragma: nocover162163 def truncate(self, size: int = None) -> int:164 raise OSError("Operation not supported") # pragma: nocover
modified:httpx/middleware/base.py+3 added-3 removed
1import typing23from ..models import AsyncRequest, AsyncResponse3from ..models import Request, Response456class BaseMiddleware:7 async def __call__(8 self, request: AsyncRequest, get_response: typing.Callable9 ) -> AsyncResponse:8 self, request: Request, get_response: typing.Callable9 ) -> Response:10 raise NotImplementedError # pragma: no cover
modified:httpx/middleware/basic_auth.py+3 added-3 removed
1import typing2from base64 import b64encode34from ..models import AsyncRequest, AsyncResponse4from ..models import Request, Response5from ..utils import to_bytes6from .base import BaseMiddleware78
3 unmodified lines
12 ):13 self.authorization_header = build_basic_auth_header(username, password)1415 async def __call__(16 self, request: AsyncRequest, get_response: typing.Callable17 ) -> AsyncResponse:16 self, request: Request, get_response: typing.Callable17 ) -> Response:18 request.headers["Authorization"] = self.authorization_header19 return await get_response(request)2021
6 unmodified lines
modified:httpx/middleware/custom_auth.py+4 added-4 removed
1import typing23from ..models import AsyncRequest, AsyncResponse3from ..models import Request, Response4from .base import BaseMiddleware567class CustomAuthMiddleware(BaseMiddleware):8 def __init__(self, auth: typing.Callable[[AsyncRequest], AsyncRequest]):8 def __init__(self, auth: typing.Callable[[Request], Request]):9 self.auth = auth1011 async def __call__(12 self, request: AsyncRequest, get_response: typing.Callable13 ) -> AsyncResponse:12 self, request: Request, get_response: typing.Callable13 ) -> Response:14 request = self.auth(request)15 return await get_response(request)
modified:httpx/middleware/digest_auth.py+4 added-4 removed
4 unmodified lines
5import typing6from urllib.request import parse_http_list78from ..exceptions import ProtocolError9from ..models import AsyncRequest, AsyncResponse, StatusCode9from ..models import Request, Response, StatusCode10from ..utils import to_bytes, to_str, unquote11from .base import BaseMiddleware1213
15 unmodified lines
29 self.username = to_bytes(username)30 self.password = to_bytes(password)3132 async def __call__(33 self, request: AsyncRequest, get_response: typing.Callable34 ) -> AsyncResponse:33 self, request: Request, get_response: typing.Callable34 ) -> Response:35 response = await get_response(request)36 if not (37 StatusCode.is_client_error(response.status_code)38 and "www-authenticate" in response.headers
9 unmodified lines
48 request.headers["Authorization"] = self._build_auth_header(request, challenge)49 return await get_response(request)5051 def _build_auth_header(52 self, request: AsyncRequest, challenge: "DigestAuthChallenge"52 self, request: Request, challenge: "DigestAuthChallenge"53 ) -> str:54 hash_func = self.ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm]5556 def digest(data: bytes) -> bytes:
125 unmodified lines
modified:httpx/middleware/redirect.py+10 added-12 removed
1 unmodified line
2import typing34from ..config import DEFAULT_MAX_REDIRECTS5from ..exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects6from ..models import URL, AsyncRequest, AsyncResponse, Cookies, Headers6from ..models import URL, Cookies, Headers, Request, Response7from ..status_codes import codes8from .base import BaseMiddleware910
6 unmodified lines
17 ):18 self.allow_redirects = allow_redirects19 self.max_redirects = max_redirects20 self.cookies = cookies21 self.history: typing.List[AsyncResponse] = []21 self.history: typing.List[Response] = []2223 async def __call__(24 self, request: AsyncRequest, get_response: typing.Callable25 ) -> AsyncResponse:24 self, request: Request, get_response: typing.Callable25 ) -> Response:26 if len(self.history) > self.max_redirects:27 raise TooManyRedirects()28 if request.url in (response.url for response in self.history):29 raise RedirectLoop()
12 unmodified lines
4243 response.call_next = functools.partial(self, next_request, get_response)44 return response4546 def build_redirect_request(47 self, request: AsyncRequest, response: AsyncResponse48 ) -> AsyncRequest:46 def build_redirect_request(self, request: Request, response: Response) -> Request:47 method = self.redirect_method(request, response)48 url = self.redirect_url(request, response)49 headers = self.redirect_headers(request, url, method) # TODO: merge headers?50 content = self.redirect_content(request, method)51 cookies = Cookies(self.cookies)54 return AsyncRequest(52 return Request(53 method=method, url=url, headers=headers, data=content, cookies=cookies54 )5558 def redirect_method(self, request: AsyncRequest, response: AsyncResponse) -> str:56 def redirect_method(self, request: Request, response: Response) -> str:57 """58 When being redirected we may want to change the method of the request59 based on certain specs or browser behavior.60 """
14 unmodified lines
75 method = "GET"7677 return method7881 def redirect_url(self, request: AsyncRequest, response: AsyncResponse) -> URL:79 def redirect_url(self, request: Request, response: Response) -> URL:80 """81 Return the URL for the redirect to follow.82 """83 location = response.headers["Location"]
10 unmodified lines
94 url = url.copy_with(fragment=request.url.fragment)9596 return url97100 def redirect_headers(self, request: AsyncRequest, url: URL, method: str) -> Headers:98 def redirect_headers(self, request: Request, url: URL, method: str) -> Headers:99 """100 Return the headers that should be used for the redirect request.101 """102 headers = Headers(request.headers)
15 unmodified lines
118 headers.pop("Cookie", None)119120 return headers121124 def redirect_content(self, request: AsyncRequest, method: str) -> bytes:122 def redirect_content(self, request: Request, method: str) -> bytes:123 """124 Return the body that should be used for the redirect request.125 """126 if method != request.method and method == "GET":
4 unmodified lines
modified:httpx/__init__.py+2 added-12 removed
1from .__version__ import __description__, __title__, __version__2from .api import delete, get, head, options, patch, post, put, request3from .client import AsyncClient, Client3from .client import Client4from .concurrency.asyncio import AsyncioBackend5from .concurrency.base import (6 BaseBackgroundManager,7 BasePoolSemaphore,
10 unmodified lines
18 TimeoutConfig,19 TimeoutTypes,20 VerifyTypes,21)22from .dispatch.base import AsyncDispatcher, Dispatcher22from .dispatch.base import Dispatcher23from .dispatch.connection import HTTPConnection24from .dispatch.connection_pool import ConnectionPool25from .dispatch.proxy_http import HTTPProxy, HTTPProxyMode26from .exceptions import (
18 unmodified lines
45)46from .middleware.digest_auth import DigestAuth47from .models import (48 URL,49 AsyncRequest,50 AsyncRequestData,51 AsyncResponse,52 AsyncResponseContent,49 AuthTypes,50 Cookies,51 CookieTypes,52 Headers,
22 unmodified lines
75 "post",76 "patch",77 "put",78 "request",83 "AsyncClient",79 "Client",80 "AsyncioBackend",81 "USER_AGENT",82 "CertTypes",
24 unmodified lines
107 "ProxyError",108 "Timeout",109 "TooManyRedirects",110 "WriteTimeout",116 "AsyncDispatcher",111 "BaseSocketStream",112 "ConcurrencyBackend",113 "Dispatcher",114 "URL",
2 unmodified lines
117 "codes",118 "TimeoutTypes",119 "HTTPVersionTypes",120 "HTTPVersionConfig",127 "AsyncRequest",128 "AsyncRequestData",129 "AsyncResponse",130 "AsyncResponseContent",121 "AuthTypes",122 "Cookies",123 "CookieTypes",124 "Headers",
11 unmodified lines
modified:httpx/api.py+42 added-40 removed
1import typing23from .client import Client4from .config import CertTypes, TimeoutTypes, VerifyTypes4from .config import DEFAULT_TIMEOUT_CONFIG, CertTypes, TimeoutTypes, VerifyTypes5from .models import (6 AuthTypes,7 CookieTypes,8 HeaderTypes,
4 unmodified lines
13 URLTypes,14)151617def request(17async def request(18 method: str,19 url: URLTypes,20 *,21 params: QueryParamTypes = None,
2 unmodified lines
24 json: typing.Any = None,25 headers: HeaderTypes = None,26 cookies: CookieTypes = None,27 auth: AuthTypes = None,28 timeout: TimeoutTypes = None,28 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,29 allow_redirects: bool = True,30 verify: VerifyTypes = True,31 cert: CertTypes = None,32 stream: bool = False,33 trust_env: bool = None,33 trust_env: bool = True,34) -> Response:35 """36 Sends an HTTP request.37
36 unmodified lines
74 Usage:7576 ```77 >>> import httpx78 >>> response = httpx.request('GET', 'https://httpbin.org/get')78 >>> response = await httpx.request('GET', 'https://httpbin.org/get')79 >>> response80 <Response [200 OK]>81 ```82 """83 async with Client(84 http_versions=["HTTP/1.1"],85 cert=cert,86 verify=verify,87 timeout=timeout,88 trust_env=trust_env,83 with Client(http_versions=["HTTP/1.1"]) as client:84 return client.request(89 ) as client:90 return await client.request(91 method=method,92 url=url,93 data=data,94 files=files,
3 unmodified lines
98 cookies=cookies,99 stream=stream,100 auth=auth,101 allow_redirects=allow_redirects,96 cert=cert,97 verify=verify,98 timeout=timeout,99 trust_env=trust_env,102 )103104103def get(105async def get(106 url: URLTypes,107 *,108 params: QueryParamTypes = None,109 headers: HeaderTypes = None,
2 unmodified lines
112 auth: AuthTypes = None,113 allow_redirects: bool = True,114 cert: CertTypes = None,115 verify: VerifyTypes = True,114 timeout: TimeoutTypes = None,115 trust_env: bool = None,116 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,117 trust_env: bool = True,118) -> Response:119 """120 Sends a `GET` request.121
1 unmodified line
123124 Note that the `data`, `files`, and `json` parameters are not available on125 this function, as `GET` requests should not include a request body.126 """125 return request(127 return await request(128 "GET",129 url,130 params=params,131 headers=headers,
7 unmodified lines
139 trust_env=trust_env,140 )141142141def options(143async def options(144 url: URLTypes,145 *,146 params: QueryParamTypes = None,147 headers: HeaderTypes = None,
2 unmodified lines
150 auth: AuthTypes = None,151 allow_redirects: bool = True,152 cert: CertTypes = None,153 verify: VerifyTypes = True,152 timeout: TimeoutTypes = None,153 trust_env: bool = None,154 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,155 trust_env: bool = True,156) -> Response:157 """158 Sends an `OPTIONS` request.159
1 unmodified line
161162 Note that the `data`, `files`, and `json` parameters are not available on163 this function, as `OPTIONS` requests should not include a request body.164 """163 return request(165 return await request(166 "OPTIONS",167 url,168 params=params,169 headers=headers,
7 unmodified lines
177 trust_env=trust_env,178 )179180179def head(181async def head(182 url: URLTypes,183 *,184 params: QueryParamTypes = None,185 headers: HeaderTypes = None,186 cookies: CookieTypes = None,187 stream: bool = False,188 auth: AuthTypes = None,187 allow_redirects: bool = False, #  Note: Differs to usual default.189 allow_redirects: bool = False, # Note: Differs to usual default.190 cert: CertTypes = None,191 verify: VerifyTypes = True,190 timeout: TimeoutTypes = None,191 trust_env: bool = None,192 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,193 trust_env: bool = True,194) -> Response:195 """196 Sends a `HEAD` request.197
3 unmodified lines
201 this function, as `HEAD` requests should not include a request body. The202 `HEAD` method also differs from the other cases in that `allow_redirects`203 defaults to `False`.204 """203 return request(205 return await request(206 "HEAD",207 url,208 params=params,209 headers=headers,
7 unmodified lines
217 trust_env=trust_env,218 )219220219def post(221async def post(222 url: URLTypes,223 *,224 data: RequestData = None,225 files: RequestFiles = None,
5 unmodified lines
231 auth: AuthTypes = None,232 allow_redirects: bool = True,233 cert: CertTypes = None,234 verify: VerifyTypes = True,233 timeout: TimeoutTypes = None,234 trust_env: bool = None,235 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,236 trust_env: bool = True,237) -> Response:238 """239 Sends a `POST` request.240241 **Parameters**: See `httpx.request`.242 """241 return request(243 return await request(244 "POST",245 url,246 data=data,247 files=files,
10 unmodified lines
258 trust_env=trust_env,259 )260261260def put(262async def put(263 url: URLTypes,264 *,265 data: RequestData = None,266 files: RequestFiles = None,
5 unmodified lines
272 auth: AuthTypes = None,273 allow_redirects: bool = True,274 cert: CertTypes = None,275 verify: VerifyTypes = True,274 timeout: TimeoutTypes = None,275 trust_env: bool = None,276 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,277 trust_env: bool = True,278) -> Response:279 """280 Sends a `PUT` request.281282 **Parameters**: See `httpx.request`.283 """282 return request(284 return await request(285 "PUT",286 url,287 data=data,288 files=files,
10 unmodified lines
299 trust_env=trust_env,300 )301302301def patch(303async def patch(304 url: URLTypes,305 *,306 data: RequestData = None,307 files: RequestFiles = None,
5 unmodified lines
313 auth: AuthTypes = None,314 allow_redirects: bool = True,315 cert: CertTypes = None,316 verify: VerifyTypes = True,315 timeout: TimeoutTypes = None,316 trust_env: bool = None,317 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,318 trust_env: bool = True,319) -> Response:320 """321 Sends a `PATCH` request.322323 **Parameters**: See `httpx.request`.324 """323 return request(325 return await request(326 "PATCH",327 url,328 data=data,329 files=files,
10 unmodified lines
340 trust_env=trust_env,341 )342343342def delete(344async def delete(345 url: URLTypes,346 *,347 params: QueryParamTypes = None,348 headers: HeaderTypes = None,
2 unmodified lines
351 auth: AuthTypes = None,352 allow_redirects: bool = True,353 cert: CertTypes = None,354 verify: VerifyTypes = True,353 timeout: TimeoutTypes = None,354 trust_env: bool = None,355 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,356 trust_env: bool = True,357) -> Response:358 """359 Sends a `DELETE` request.360
1 unmodified line
362363 Note that the `data`, `files`, and `json` parameters are not available on364 this function, as `DELETE` requests should not include a request body.365 """364 return request(366 return await request(367 "DELETE",368 url,369 params=params,370 headers=headers,
9 unmodified lines
modified:httpx/client.py+88 added-591 removed
1import functools2import inspect2import netrc3import typing4from types import TracebackType5
11 unmodified lines
17 TimeoutTypes,18 VerifyTypes,19)20from .dispatch.asgi import ASGIDispatch22from .dispatch.base import AsyncDispatcher, Dispatcher21from .dispatch.base import Dispatcher22from .dispatch.connection_pool import ConnectionPool23from .dispatch.proxy_http import HTTPProxy25from .dispatch.threaded import ThreadedDispatcher26from .dispatch.wsgi import WSGIDispatch24from .exceptions import HTTPError, InvalidURL25from .middleware.base import BaseMiddleware26from .middleware.basic_auth import BasicAuthMiddleware27from .middleware.custom_auth import CustomAuthMiddleware28from .middleware.redirect import RedirectMiddleware29from .models import (30 URL,34 AsyncRequest,35 AsyncRequestData,36 AsyncResponse,37 AsyncResponseContent,31 AuthTypes,32 Cookies,33 CookieTypes,34 Headers,35 HeaderTypes,36 ProxiesTypes,37 QueryParams,38 QueryParamTypes,39 Request,40 RequestData,41 RequestFiles,42 Response,49 ResponseContent,43 URLTypes,44)45from .utils import ElapsedTimer, get_environment_proxies, get_logger, get_netrc4647logger = get_logger(__name__)484957class BaseClient:50class Client:51 """52 An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.5354 Usage:5556 ```57 >>> client = httpx.Client()58 >>> response = client.get('https://example.org')59 ```6061 **Parameters:**6263 * **auth** - *(optional)* An authentication class to use when sending64 requests.65 * **params** - *(optional)* Query parameters to include in request URLs, as66 a string, dictionary, or list of two-tuples.67 * **headers** - *(optional)* Dictionary of HTTP headers to include when68 sending requests.69 * **cookies** - *(optional)* Dictionary of Cookie items to include when70 sending requests.71 * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to72 verify the identity of requested hosts. Either `True` (default CA bundle),73 a path to an SSL certificate file, or `False` (disable verification).74 * **cert** - *(optional)* An SSL certificate used by the requested host75 to authenticate the client. Either a path to an SSL certificate file, or76 two-tuple of (certificate file, key file), or a three-tuple of (certificate77 file, key file, password).78 * **http_versions** - *(optional)* A list of strings of HTTP protocol79 versions to use when sending requests. eg. `http_versions=["HTTP/1.1"]`80 * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy81 URLs.82 * **timeout** - *(optional)* The timeout configuration to use when sending83 requests.84 * **pool_limits** - *(optional)* The connection pool configuration to use85 when determining the maximum number of concurrently open HTTP connections.86 * **max_redirects** - *(optional)* The maximum number of redirect responses87 that should be followed.88 * **base_url** - *(optional)* A URL to use as the base when building89 request URLs.90 * **dispatch** - *(optional)* A dispatch class to use for sending requests91 over the network.92 * **app** - *(optional)* An ASGI application to send requests to,93 rather than sending actual network requests.94 * **backend** - *(optional)* A concurrency backend to use when issuing95 async requests.96 * **trust_env** - *(optional)* Enables or disables usage of environment97 variables for configuration.98 * **uds** - *(optional)* A path to a Unix domain socket to connect through.99 """100101 def __init__(102 self,103 *,104 auth: AuthTypes = None,
7 unmodified lines
112 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,113 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,114 max_redirects: int = DEFAULT_MAX_REDIRECTS,115 base_url: URLTypes = None,73 dispatch: typing.Union[AsyncDispatcher, Dispatcher] = None,116 dispatch: Dispatcher = None,117 app: typing.Callable = None,118 backend: ConcurrencyBackend = None,119 trust_env: bool = True,120 uds: str = None,121 ):122 if backend is None:123 backend = AsyncioBackend()12482 self.check_concurrency_backend(backend)83125 if app is not None:85 param_count = len(inspect.signature(app).parameters)86 assert param_count in (2, 3)87 if param_count == 2:88 dispatch = WSGIDispatch(app=app)89 else:90 dispatch = ASGIDispatch(app=app, backend=backend)126 dispatch = ASGIDispatch(app=app, backend=backend)127128 self.trust_env = True if trust_env is None else trust_env129130 if dispatch is None:95 async_dispatch: AsyncDispatcher = ConnectionPool(131 dispatch = ConnectionPool(132 verify=verify,133 cert=cert,134 timeout=timeout,135 http_versions=http_versions,
1 unmodified line
137 backend=backend,138 trust_env=self.trust_env,139 uds=uds,140 )105 elif isinstance(dispatch, Dispatcher):106 async_dispatch = ThreadedDispatcher(dispatch, backend)107 else:108 async_dispatch = dispatch141142 if base_url is None:143 self.base_url = URL("", allow_relative=True)144 else:
6 unmodified lines
151 self._params = QueryParams(params)152 self._headers = Headers(headers)153 self._cookies = Cookies(cookies)154 self.max_redirects = max_redirects123 self.dispatch = async_dispatch155 self.dispatch = dispatch156 self.concurrency_backend = backend157158 if proxies is None and trust_env:159 proxies = typing.cast(ProxiesTypes, get_environment_proxies())160129 self.proxies: typing.Dict[str, AsyncDispatcher] = _proxies_to_dispatchers(161 self.proxies: typing.Dict[str, Dispatcher] = _proxies_to_dispatchers(162 proxies,163 verify=verify,164 cert=cert,165 timeout=timeout,
35 unmodified lines
201 @params.setter202 def params(self, params: QueryParamTypes) -> None:203 self._params = QueryParams(params)204173 def check_concurrency_backend(self, backend: ConcurrencyBackend) -> None:174 pass # pragma: no cover175205 def merge_url(self, url: URLTypes) -> URL:206 url = self.base_url.join(relative_url=url)207 if url.scheme == "http" and hstspreload.in_hsts_preload(url.host):208 url = url.copy_with(scheme="https")
27 unmodified lines
236 return params237238 async def _get_response(239 self,211 request: AsyncRequest,240 request: Request,241 *,242 stream: bool = False,243 auth: AuthTypes = None,244 allow_redirects: bool = True,245 verify: VerifyTypes = None,246 cert: CertTypes = None,247 timeout: TimeoutTypes = None,248 trust_env: bool = None,220 ) -> AsyncResponse:249 ) -> Response:250 if request.url.scheme not in ("http", "https"):251 raise InvalidURL('URL scheme must be "http" or "https".')252253 dispatch = self._dispatcher_for_request(request, self.proxies)254226 async def get_response(request: AsyncRequest) -> AsyncResponse:255 async def get_response(request: Request) -> Response:256 try:257 with ElapsedTimer() as timer:258 response = await dispatch.send(259 request, verify=verify, cert=cert, timeout=timeout260 )261 response.elapsed = timer.elapsed262 response.request = request263 except HTTPError as exc:264 # Add the original request to any HTTPError unless265 # there'a already a request attached in the case of266 # a ProxyError.
37 unmodified lines
304305 return await get_response(request)306307 def _get_auth_middleware(278 self, request: AsyncRequest, trust_env: bool, auth: AuthTypes = None308 self, request: Request, trust_env: bool, auth: AuthTypes = None309 ) -> typing.Optional[BaseMiddleware]:310 if isinstance(auth, tuple):311 return BasicAuthMiddleware(username=auth[0], password=auth[1])312 elif isinstance(auth, BaseMiddleware):
3 unmodified lines
316317 if auth is not None:318 raise TypeError(319 'When specified, "auth" must be a (username, password) tuple or '290 "a callable with signature (AsyncRequest) -> AsyncRequest "320 "a callable with signature (Request) -> Request "321 f"(got {auth!r})"322 )323324 if request.url.username or request.url.password:
16 unmodified lines
341 def _get_netrc(self) -> typing.Optional[netrc.netrc]:342 return get_netrc()343344 def _dispatcher_for_request(315 self, request: AsyncRequest, proxies: typing.Dict[str, AsyncDispatcher]316 ) -> AsyncDispatcher:317 """Gets the AsyncDispatcher instance that should be used for a given Request"""345 self, request: Request, proxies: typing.Dict[str, Dispatcher]346 ) -> Dispatcher:347 """Gets the Dispatcher instance that should be used for a given Request"""348 if proxies:349 url = request.url350 is_default_port = (url.scheme == "http" and url.port == 80) or (351 url.scheme == "https" and url.port == 443
18 unmodified lines
370 self,371 method: str,372 url: URLTypes,373 *,344 data: AsyncRequestData = None,374 data: RequestData = None,375 files: RequestFiles = None,376 json: typing.Any = None,377 params: QueryParamTypes = None,378 headers: HeaderTypes = None,379 cookies: CookieTypes = None,350 ) -> AsyncRequest:380 ) -> Request:381 """382 Build and return a request instance.383 """384 url = self.merge_url(url)385 headers = self.merge_headers(headers)386 cookies = self.merge_cookies(cookies)387 params = self.merge_queryparams(params)358 return AsyncRequest(388 return Request(389 method,390 url,391 data=data,392 files=files,
2 unmodified lines
395 headers=headers,396 cookies=cookies,397 )398369370class AsyncClient(BaseClient):399 async def get(400 self,401 url: URLTypes,402 *,
6 unmodified lines
409 cert: CertTypes = None,410 verify: VerifyTypes = None,411 timeout: TimeoutTypes = None,412 trust_env: bool = None,385 ) -> AsyncResponse:413 ) -> Response:414 return await self.request(415 "GET",416 url,417 params=params,
21 unmodified lines
439 cert: CertTypes = None,440 verify: VerifyTypes = None,441 timeout: TimeoutTypes = None,442 trust_env: bool = None,415 ) -> AsyncResponse:443 ) -> Response:444 return await self.request(445 "OPTIONS",446 url,447 params=params,
21 unmodified lines
469 cert: CertTypes = None,470 verify: VerifyTypes = None,471 timeout: TimeoutTypes = None,472 trust_env: bool = None,445 ) -> AsyncResponse:473 ) -> Response:474 return await self.request(475 "HEAD",476 url,477 params=params,
11 unmodified lines
489 async def post(490 self,491 url: URLTypes,492 *,465 data: AsyncRequestData = None,493 data: RequestData = None,494 files: RequestFiles = None,495 json: typing.Any = None,496 params: QueryParamTypes = None,497 headers: HeaderTypes = None,
4 unmodified lines
502 cert: CertTypes = None,503 verify: VerifyTypes = None,504 timeout: TimeoutTypes = None,505 trust_env: bool = None,478 ) -> AsyncResponse:506 ) -> Response:507 return await self.request(508 "POST",509 url,510 data=data,
14 unmodified lines
525 async def put(526 self,527 url: URLTypes,528 *,501 data: AsyncRequestData = None,529 data: RequestData = None,530 files: RequestFiles = None,531 json: typing.Any = None,532 params: QueryParamTypes = None,533 headers: HeaderTypes = None,
4 unmodified lines
538 cert: CertTypes = None,539 verify: VerifyTypes = None,540 timeout: TimeoutTypes = None,541 trust_env: bool = None,514 ) -> AsyncResponse:542 ) -> Response:543 return await self.request(544 "PUT",545 url,546 data=data,
14 unmodified lines
561 async def patch(562 self,563 url: URLTypes,564 *,537 data: AsyncRequestData = None,565 data: RequestData = None,566 files: RequestFiles = None,567 json: typing.Any = None,568 params: QueryParamTypes = None,569 headers: HeaderTypes = None,
4 unmodified lines
574 cert: CertTypes = None,575 verify: VerifyTypes = None,576 timeout: TimeoutTypes = None,577 trust_env: bool = None,550 ) -> AsyncResponse:578 ) -> Response:579 return await self.request(580 "PATCH",581 url,582 data=data,
24 unmodified lines
607 cert: CertTypes = None,608 verify: VerifyTypes = None,609 timeout: TimeoutTypes = None,610 trust_env: bool = None,583 ) -> AsyncResponse:611 ) -> Response:612 return await self.request(613 "DELETE",614 url,615 params=params,
12 unmodified lines
628 self,629 method: str,630 url: URLTypes,631 *,604 data: AsyncRequestData = None,632 data: RequestData = None,633 files: RequestFiles = None,634 json: typing.Any = None,635 params: QueryParamTypes = None,636 headers: HeaderTypes = None,
4 unmodified lines
641 cert: CertTypes = None,642 verify: VerifyTypes = None,643 timeout: TimeoutTypes = None,644 trust_env: bool = None,617 ) -> AsyncResponse:645 ) -> Response:646 request = self.build_request(647 method=method,648 url=url,649 data=data,
16 unmodified lines
666 return response667668 async def send(669 self,642 request: AsyncRequest,670 request: Request,671 *,672 stream: bool = False,673 auth: AuthTypes = None,674 allow_redirects: bool = True,675 verify: VerifyTypes = None,676 cert: CertTypes = None,677 timeout: TimeoutTypes = None,678 trust_env: bool = None,651 ) -> AsyncResponse:679 ) -> Response:680 return await self._get_response(681 request=request,682 stream=stream,683 auth=auth,
6 unmodified lines
690691 async def close(self) -> None:692 await self.dispatch.close()693666 async def __aenter__(self) -> "AsyncClient":694 async def __aenter__(self) -> "Client":695 return self696697 async def __aexit__(698 self,
3 unmodified lines
702 ) -> None:703 await self.close()704705678class Client(BaseClient):679 """680 An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.681682 Usage:683684 ```685 >>> client = httpx.Client()686 >>> response = client.get('https://example.org')687 ```688689 **Parameters:**690691 * **auth** - *(optional)* An authentication class to use when sending692 requests.693 * **params** - *(optional)* Query parameters to include in request URLs, as694 a string, dictionary, or list of two-tuples.695 * **headers** - *(optional)* Dictionary of HTTP headers to include when696 sending requests.697 * **cookies** - *(optional)* Dictionary of Cookie items to include when698 sending requests.699 * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to700 verify the identity of requested hosts. Either `True` (default CA bundle),701 a path to an SSL certificate file, or `False` (disable verification).702 * **cert** - *(optional)* An SSL certificate used by the requested host703 to authenticate the client. Either a path to an SSL certificate file, or704 two-tuple of (certificate file, key file), or a three-tuple of (certificate705 file, key file, password).706 * **http_versions** - *(optional)* A list of strings of HTTP protocol707 versions to use when sending requests. eg. `http_versions=["HTTP/1.1"]`708 * **proxies** - *(optional)* A dictionary mapping HTTP protocols to proxy709 URLs.710 * **timeout** - *(optional)* The timeout configuration to use when sending711 requests.712 * **pool_limits** - *(optional)* The connection pool configuration to use713 when determining the maximum number of concurrently open HTTP connections.714 * **max_redirects** - *(optional)* The maximum number of redirect responses715 that should be followed.716 * **base_url** - *(optional)* A URL to use as the base when building717 request URLs.718 * **dispatch** - *(optional)* A dispatch class to use for sending requests719 over the network.720 * **app** - *(optional)* A WSGI or ASGI application to send requests to,721 rather than sending actual network requests.722 * **backend** - *(optional)* A concurrency backend to use when issuing723 async requests.724 * **trust_env** - *(optional)* Enables or disables usage of environment725 variables for configuration.726 * **uds** - *(optional)* A path to a Unix domain socket to connect through.727 """728729 def check_concurrency_backend(self, backend: ConcurrencyBackend) -> None:730 # Iterating over response content allocates an async environment on each step.731 # This is relatively cheap on asyncio, but cannot be guaranteed for all732 # concurrency backends.733 # The sync client performs I/O on its own, so it doesn't need to support734 # arbitrary concurrency backends.735 # Therefore, we keep the `backend` parameter (for testing/mocking), but require736 # that the concurrency backend relies on asyncio.737738 if isinstance(backend, AsyncioBackend):739 return740741 if hasattr(backend, "loop"):742 # Most likely a proxy class.743 return744745 raise ValueError("'Client' only supports asyncio-based concurrency backends")746747 def _async_request_data(748 self, data: RequestData = None749 ) -> typing.Optional[AsyncRequestData]:750 """751 If the request data is an bytes iterator then return an async bytes752 iterator onto the request data.753 """754 if data is None or isinstance(data, (str, bytes, dict)):755 return data756757 # Coerce an iterator into an async iterator, with each item in the758 # iteration running as a thread-pooled operation.759 assert hasattr(data, "__iter__")760 return self.concurrency_backend.iterate_in_threadpool(data)761762 def _sync_data(self, data: AsyncResponseContent) -> ResponseContent:763 if isinstance(data, bytes):764 return data765766 # Coerce an async iterator into an iterator, with each item in the767 # iteration run within the event loop.768 assert hasattr(data, "__aiter__")769 return self.concurrency_backend.iterate(data)770771 def request(772 self,773 method: str,774 url: URLTypes,775 *,776 data: RequestData = None,777 files: RequestFiles = None,778 json: typing.Any = None,779 params: QueryParamTypes = None,780 headers: HeaderTypes = None,781 cookies: CookieTypes = None,782 stream: bool = False,783 auth: AuthTypes = None,784 allow_redirects: bool = True,785 verify: VerifyTypes = None,786 cert: CertTypes = None,787 timeout: TimeoutTypes = None,788 trust_env: bool = None,789 ) -> Response:790 """791 Sends an HTTP request.792793 **Parameters:**794795 * **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`,796 `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`.797 * **url** - URL for the new `Request` object.798 * **data** - *(optional)* Data to include in the body of the request, as a799 dictionary800 * **files** - *(optional)* A dictionary of upload files to include in the801 body of the request.802 * **json** - *(optional)* A JSON serializable object to include in the body803 of the request.804 * **params** - *(optional)* Query parameters to include in the URL, as a805 string, dictionary, or list of two-tuples.806 * **headers** - *(optional)* Dictionary of HTTP headers to include on the807 request.808 * **cookies** - *(optional)* Dictionary of Cookie items to include in the809 request.810 * **stream** - *(optional)* Enable/disable streaming responses.811 * **auth** - *(optional)* An authentication class to use when sending the812 request.813 * **allow_redirects** - *(optional)* Enables or disables HTTP redirects.814 * **verify** - *(optional)* SSL certificates (a.k.a CA bundle) used to815 verify the identity of requested hosts. Either `True` (default CA bundle),816 a path to an SSL certificate file, or `False` (disable verification).817 * **cert** - *(optional)* An SSL certificate used by the requested host818 to authenticate the client. Either a path to an SSL certificate file, or819 two-tuple of (certificate file, key file), or a three-tuple of (certificate820 file, key file, password).821 * **timeout** - *(optional)* The timeout configuration to use when sending822 the request.823 * **trust_env** - *(optional)* Enables or disables usage of environment824 variables for configuration.825826 **Returns:** `Response`827828 Usage:829830 ```831 >>> import httpx832 >>> client = httpx.Client()833 >>> response = client.request('GET', 'https://httpbin.org/get')834 >>> response835 <Response [200 OK]>836 ```837 """838 request = self.build_request(839 method=method,840 url=url,841 data=self._async_request_data(data),842 files=files,843 json=json,844 params=params,845 headers=headers,846 cookies=cookies,847 )848 return self.send(849 request,850 stream=stream,851 auth=auth,852 allow_redirects=allow_redirects,853 verify=verify,854 cert=cert,855 timeout=timeout,856 trust_env=trust_env,857 )858859 def send(860 self,861 request: AsyncRequest,862 *,863 stream: bool = False,864 auth: AuthTypes = None,865 allow_redirects: bool = True,866 verify: VerifyTypes = None,867 cert: CertTypes = None,868 timeout: TimeoutTypes = None,869 trust_env: bool = None,870 ) -> Response:871 """872 Sends a request over the network, returning a response.873 """874 concurrency_backend = self.concurrency_backend875876 coroutine = self._get_response877 args = [request]878 kwargs = {879 "stream": True,880 "auth": auth,881 "allow_redirects": allow_redirects,882 "verify": verify,883 "cert": cert,884 "timeout": timeout,885 "trust_env": trust_env,886 }887 async_response = concurrency_backend.run(coroutine, *args, **kwargs)888889 content = getattr(890 async_response, "_raw_content", getattr(async_response, "_raw_stream", None)891 )892893 sync_content = self._sync_data(content)894895 def sync_on_close() -> None:896 nonlocal concurrency_backend, async_response897 concurrency_backend.run(async_response.on_close)898899 response = Response(900 status_code=async_response.status_code,901 http_version=async_response.http_version,902 headers=async_response.headers,903 content=sync_content,904 on_close=sync_on_close,905 request=async_response.request,906 history=async_response.history,907 elapsed=async_response.elapsed,908 )909 if not stream:910 try:911 response.read()912 finally:913 response.close()914 return response915916 def get(917 self,918 url: URLTypes,919 *,920 params: QueryParamTypes = None,921 headers: HeaderTypes = None,922 cookies: CookieTypes = None,923 stream: bool = False,924 auth: AuthTypes = None,925 allow_redirects: bool = True,926 cert: CertTypes = None,927 verify: VerifyTypes = None,928 timeout: TimeoutTypes = None,929 trust_env: bool = None,930 ) -> Response:931 """932 Sends a `GET` request.933934 **Parameters**: See `Client.request`.935936 Note that the `data`, `files`, and `json` parameters are not available on937 this function, as `GET` requests should not include a request body.938 """939 return self.request(940 "GET",941 url,942 params=params,943 headers=headers,944 cookies=cookies,945 stream=stream,946 auth=auth,947 allow_redirects=allow_redirects,948 verify=verify,949 cert=cert,950 timeout=timeout,951 trust_env=trust_env,952 )953954 def options(955 self,956 url: URLTypes,957 *,958 params: QueryParamTypes = None,959 headers: HeaderTypes = None,960 cookies: CookieTypes = None,961 stream: bool = False,962 auth: AuthTypes = None,963 allow_redirects: bool = True,964 cert: CertTypes = None,965 verify: VerifyTypes = None,966 timeout: TimeoutTypes = None,967 trust_env: bool = None,968 ) -> Response:969 """970 Sends an `OPTIONS` request.971972 **Parameters**: See `Client.request`.973974 Note that the `data`, `files`, and `json` parameters are not available on975 this function, as `OPTIONS` requests should not include a request body.976 """977 return self.request(978 "OPTIONS",979 url,980 params=params,981 headers=headers,982 cookies=cookies,983 stream=stream,984 auth=auth,985 allow_redirects=allow_redirects,986 verify=verify,987 cert=cert,988 timeout=timeout,989 trust_env=trust_env,990 )991992 def head(993 self,994 url: URLTypes,995 *,996 params: QueryParamTypes = None,997 headers: HeaderTypes = None,998 cookies: CookieTypes = None,999 stream: bool = False,1000 auth: AuthTypes = None,1001 allow_redirects: bool = False, # NOTE: Differs to usual default.1002 cert: CertTypes = None,1003 verify: VerifyTypes = None,1004 timeout: TimeoutTypes = None,1005 trust_env: bool = None,1006 ) -> Response:1007 """1008 Sends a `HEAD` request.10091010 **Parameters**: See `Client.request`.10111012 Note that the `data`, `files`, and `json` parameters are not available on1013 this function, as `HEAD` requests should not include a request body. The1014 `HEAD` method also differs from the other cases in that `allow_redirects`1015 defaults to `False`.1016 """1017 return self.request(1018 "HEAD",1019 url,1020 params=params,1021 headers=headers,1022 cookies=cookies,1023 stream=stream,1024 auth=auth,1025 allow_redirects=allow_redirects,1026 verify=verify,1027 cert=cert,1028 timeout=timeout,1029 trust_env=trust_env,1030 )10311032 def post(1033 self,1034 url: URLTypes,1035 *,1036 data: RequestData = None,1037 files: RequestFiles = None,1038 json: typing.Any = None,1039 params: QueryParamTypes = None,1040 headers: HeaderTypes = None,1041 cookies: CookieTypes = None,1042 stream: bool = False,1043 auth: AuthTypes = None,1044 allow_redirects: bool = True,1045 cert: CertTypes = None,1046 verify: VerifyTypes = None,1047 timeout: TimeoutTypes = None,1048 trust_env: bool = None,1049 ) -> Response:1050 """1051 Sends a `POST` request.10521053 **Parameters**: See `Client.request`.1054 """1055 return self.request(1056 "POST",1057 url,1058 data=data,1059 files=files,1060 json=json,1061 params=params,1062 headers=headers,1063 cookies=cookies,1064 stream=stream,1065 auth=auth,1066 allow_redirects=allow_redirects,1067 verify=verify,1068 cert=cert,1069 timeout=timeout,1070 trust_env=trust_env,1071 )10721073 def put(1074 self,1075 url: URLTypes,1076 *,1077 data: RequestData = None,1078 files: RequestFiles = None,1079 json: typing.Any = None,1080 params: QueryParamTypes = None,1081 headers: HeaderTypes = None,1082 cookies: CookieTypes = None,1083 stream: bool = False,1084 auth: AuthTypes = None,1085 allow_redirects: bool = True,1086 cert: CertTypes = None,1087 verify: VerifyTypes = None,1088 timeout: TimeoutTypes = None,1089 trust_env: bool = None,1090 ) -> Response:1091 """1092 Sends a `PUT` request.10931094 **Parameters**: See `Client.request`.1095 """1096 return self.request(1097 "PUT",1098 url,1099 data=data,1100 files=files,1101 json=json,1102 params=params,1103 headers=headers,1104 cookies=cookies,1105 stream=stream,1106 auth=auth,1107 allow_redirects=allow_redirects,1108 verify=verify,1109 cert=cert,1110 timeout=timeout,1111 trust_env=trust_env,1112 )11131114 def patch(1115 self,1116 url: URLTypes,1117 *,1118 data: RequestData = None,1119 files: RequestFiles = None,1120 json: typing.Any = None,1121 params: QueryParamTypes = None,1122 headers: HeaderTypes = None,1123 cookies: CookieTypes = None,1124 stream: bool = False,1125 auth: AuthTypes = None,1126 allow_redirects: bool = True,1127 cert: CertTypes = None,1128 verify: VerifyTypes = None,1129 timeout: TimeoutTypes = None,1130 trust_env: bool = None,1131 ) -> Response:1132 """1133 Sends a `PATCH` request.11341135 **Parameters**: See `Client.request`.1136 """1137 return self.request(1138 "PATCH",1139 url,1140 data=data,1141 files=files,1142 json=json,1143 params=params,1144 headers=headers,1145 cookies=cookies,1146 stream=stream,1147 auth=auth,1148 allow_redirects=allow_redirects,1149 verify=verify,1150 cert=cert,1151 timeout=timeout,1152 trust_env=trust_env,1153 )11541155 def delete(1156 self,1157 url: URLTypes,1158 *,1159 params: QueryParamTypes = None,1160 headers: HeaderTypes = None,1161 cookies: CookieTypes = None,1162 stream: bool = False,1163 auth: AuthTypes = None,1164 allow_redirects: bool = True,1165 cert: CertTypes = None,1166 verify: VerifyTypes = None,1167 timeout: TimeoutTypes = None,1168 trust_env: bool = None,1169 ) -> Response:1170 """1171 Sends a `DELETE` request.11721173 **Parameters**: See `Client.request`.1174 """1175 return self.request(1176 "DELETE",1177 url,1178 params=params,1179 headers=headers,1180 cookies=cookies,1181 stream=stream,1182 auth=auth,1183 allow_redirects=allow_redirects,1184 verify=verify,1185 cert=cert,1186 timeout=timeout,1187 trust_env=trust_env,1188 )11891190 def close(self) -> None:1191 """1192 Close any open connections in the connection pool.1193 """1194 coroutine = self.dispatch.close1195 self.concurrency_backend.run(coroutine)11961197 def __enter__(self) -> "Client":1198 return self11991200 def __exit__(1201 self,1202 exc_type: typing.Type[BaseException] = None,1203 exc_value: BaseException = None,1204 traceback: TracebackType = None,1205 ) -> None:1206 self.close()12071208706def _proxies_to_dispatchers(707 proxies: typing.Optional[ProxiesTypes],708 verify: VerifyTypes,709 cert: typing.Optional[CertTypes],
1 unmodified line
711 http_versions: typing.Optional[HTTPVersionTypes],712 pool_limits: PoolLimits,713 backend: ConcurrencyBackend,714 trust_env: bool,1218) -> typing.Dict[str, AsyncDispatcher]:1219 def _proxy_from_url(url: URLTypes) -> AsyncDispatcher:715) -> typing.Dict[str, Dispatcher]:716 def _proxy_from_url(url: URLTypes) -> Dispatcher:717 nonlocal verify, cert, timeout, http_versions, pool_limits, backend, trust_env718 url = URL(url)719 if url.scheme in ("http", "https"):720 return HTTPProxy(
11 unmodified lines
732 if proxies is None:733 return {}734 elif isinstance(proxies, (str, URL)):735 return {"all": _proxy_from_url(proxies)}1239 elif isinstance(proxies, AsyncDispatcher):736 elif isinstance(proxies, Dispatcher):737 return {"all": proxies}738 else:739 new_proxies = {}740 for key, dispatcher_or_url in proxies.items():
5 unmodified lines
modified:httpx/exceptions.py+2 added-5 removed
1import typing23if typing.TYPE_CHECKING:4 from .models import BaseRequest, BaseResponse # pragma: nocover4 from .models import Request, Response # pragma: nocover567class HTTPError(Exception):8 """9 Base class for Httpx exception10 """1112 def __init__(13 self,14 *args: typing.Any,15 request: "BaseRequest" = None,16 response: "BaseResponse" = None,13 self, *args: typing.Any, request: "Request" = None, response: "Response" = None14 ) -> None:15 self.response = response16 self.request = request or getattr(self.response, "request", None)17 super().__init__(*args)
142 unmodified lines
modified:httpx/models.py+44 added-226 removed
42 unmodified lines
43)4445if typing.TYPE_CHECKING: # pragma: no cover46 from .middleware.base import BaseMiddleware # noqa: F40147 from .dispatch.base import AsyncDispatcher # noqa: F40147 from .dispatch.base import Dispatcher # noqa: F4014849PrimitiveData = typing.Optional[typing.Union[str, int, float, bool]]5051URLTypes = typing.Union["URL", str]
14 unmodified lines
66CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]6768AuthTypes = typing.Union[69 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],70 typing.Callable[["AsyncRequest"], "AsyncRequest"],70 typing.Callable[["Request"], "Request"],71 "BaseMiddleware",72]7374ProxiesTypes = typing.Union[75 URLTypes,76 "AsyncDispatcher",77 typing.Dict[URLTypes, typing.Union[URLTypes, "AsyncDispatcher"]],75 URLTypes, "Dispatcher", typing.Dict[URLTypes, typing.Union[URLTypes, "Dispatcher"]]76]7780AsyncRequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]78RequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]7982RequestData = typing.Union[dict, str, bytes, typing.Iterator[bytes]]8380RequestFiles = typing.Dict[81 str,82 typing.Union[83 typing.IO[typing.AnyStr], # file
3 unmodified lines
87 ], # (filename, file, content_type)88 ],89]9095AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]91ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]9297ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]939994class URL:95 def __init__(96 self,97 url: URLTypes,
487 unmodified lines
585 return f"{class_name}({as_dict!r}{encoding_str})"586 return f"{class_name}({as_list!r}{encoding_str})"587588595class BaseRequest:589class Request:590 def __init__(591 self,592 method: str,593 url: typing.Union[str, URL],594 *,595 params: QueryParamTypes = None,596 headers: HeaderTypes = None,597 cookies: CookieTypes = None,598 data: RequestData = None,599 files: RequestFiles = None,600 json: typing.Any = None,601 ):602 self.method = method.upper()603 self.url = URL(url, params=params)604 self.headers = Headers(headers)605 if cookies:606 self._cookies = Cookies(cookies)607 self._cookies.set_cookie_header(self)608 if data is None or isinstance(data, dict):609 content, content_type = self.encode_data(data, files, json)610 self.is_streaming = False611 self.content = content612 if content_type:613 self.headers["Content-Type"] = content_type614 elif isinstance(data, (str, bytes)):615 data = data.encode("utf-8") if isinstance(data, str) else data616 self.is_streaming = False617 self.content = data618 else:619 assert hasattr(data, "__aiter__")620 self.is_streaming = True621 self.content_aiter = data622 self.prepare()623624 def encode_data(625 self, data: dict = None, files: RequestFiles = None, json: typing.Any = None626 ) -> typing.Tuple[bytes, str]:
58 unmodified lines
685 class_name = self.__class__.__name__686 url = str(self.url)687 return f"<{class_name}({self.method!r}, {url!r})>"688677678class AsyncRequest(BaseRequest):679 def __init__(680 self,681 method: str,682 url: typing.Union[str, URL],683 *,684 params: QueryParamTypes = None,685 headers: HeaderTypes = None,686 cookies: CookieTypes = None,687 data: AsyncRequestData = None,688 files: RequestFiles = None,689 json: typing.Any = None,690 ):691 super().__init__(692 method=method, url=url, params=params, headers=headers, cookies=cookies693 )694695 if data is None or isinstance(data, dict):696 content, content_type = self.encode_data(data, files, json)697 self.is_streaming = False698 self.content = content699 if content_type:700 self.headers["Content-Type"] = content_type701 elif isinstance(data, (str, bytes)):702 data = data.encode("utf-8") if isinstance(data, str) else data703 self.is_streaming = False704 self.content = data705 else:706 assert hasattr(data, "__aiter__")707 self.is_streaming = True708 self.content_aiter = data709 self.prepare()710689 async def read(self) -> bytes:690 """691 Read and return the response content.692 """
8 unmodified lines
701 elif self.content:702 yield self.content703704727class Request(BaseRequest):705class Response:706 def __init__(707 self,730 method: str,731 url: typing.Union[str, URL],732 *,733 params: QueryParamTypes = None,734 headers: HeaderTypes = None,735 cookies: CookieTypes = None,736 data: RequestData = None,737 files: RequestFiles = None,738 json: typing.Any = None,739 ):740 super().__init__(741 method=method, url=url, params=params, headers=headers, cookies=cookies742 )743744 if data is None or isinstance(data, dict):745 content, content_type = self.encode_data(data, files, json)746 self.is_streaming = False747 self.content = content748 if content_type:749 self.headers["Content-Type"] = content_type750 elif isinstance(data, (str, bytes)):751 data = data.encode("utf-8") if isinstance(data, str) else data752 self.is_streaming = False753 self.content = data754 else:755 assert hasattr(data, "__iter__")756 self.is_streaming = True757 self.content_iter = data758759 self.prepare()760761 def read(self) -> bytes:762 if not hasattr(self, "content"):763 self.content = b"".join([part for part in self.stream()])764 return self.content765766 def stream(self) -> typing.Iterator[bytes]:767 if self.is_streaming:768 for part in self.content_iter:769 yield part770 elif self.content:771 yield self.content772773774class BaseResponse:775 def __init__(776 self,708 status_code: int,709 *,710 http_version: str = None,711 headers: HeaderTypes = None,781 request: BaseRequest = None,712 content: ResponseContent = None,713 on_close: typing.Callable = None,714 request: Request = None,715 history: typing.List["Response"] = None,716 elapsed: datetime.timedelta = None,717 ):718 self.status_code = status_code719 self.http_version = http_version
3 unmodified lines
723 self.on_close = on_close724 self.elapsed = datetime.timedelta(0) if elapsed is None else elapsed725 self.call_next: typing.Optional[typing.Callable] = None726727 self.history = [] if history is None else list(history)728729 if content is None or isinstance(content, bytes):730 self.is_closed = True731 self.is_stream_consumed = True732 self._raw_content = content or b""733 else:734 self.is_closed = False735 self.is_stream_consumed = False736 self._raw_stream = content737738 @property739 def reason_phrase(self) -> str:740 return StatusCode.get_reason_phrase(self.status_code)741
155 unmodified lines
897898 def __repr__(self) -> str:899 return f"<Response [{self.status_code} {self.reason_phrase}]>"900957958class AsyncResponse(BaseResponse):959 def __init__(960 self,961 status_code: int,962 *,963 http_version: str = None,964 headers: HeaderTypes = None,965 content: AsyncResponseContent = None,966 on_close: typing.Callable = None,967 request: AsyncRequest = None,968 history: typing.List["BaseResponse"] = None,969 elapsed: datetime.timedelta = None,970 ):971 super().__init__(972 status_code=status_code,973 http_version=http_version,974 headers=headers,975 request=request,976 on_close=on_close,977 elapsed=elapsed,978 )979980 self.history = [] if history is None else list(history)981982 if content is None or isinstance(content, bytes):983 self.is_closed = True984 self.is_stream_consumed = True985 self._raw_content = content or b""986 else:987 self.is_closed = False988 self.is_stream_consumed = False989 self._raw_stream = content990901 async def read(self) -> bytes:902 """903 Read and return the response content.904 """
40 unmodified lines
945 async for part in self._raw_stream:946 yield part947 await self.close()9481039 async def next(self) -> "AsyncResponse":949 async def next(self) -> "Response":950 """951 Get the next response from a redirect response.952 """953 if not self.is_redirect:
11 unmodified lines
965 if self.on_close is not None:966 await self.on_close()9679681059class Response(BaseResponse):1060 def __init__(1061 self,1062 status_code: int,1063 *,1064 http_version: str = None,1065 headers: HeaderTypes = None,1066 content: ResponseContent = None,1067 on_close: typing.Callable = None,1068 request: Request = None,1069 history: typing.List["BaseResponse"] = None,1070 elapsed: datetime.timedelta = None,1071 ):1072 super().__init__(1073 status_code=status_code,1074 http_version=http_version,1075 headers=headers,1076 request=request,1077 on_close=on_close,1078 elapsed=elapsed,1079 )10801081 self.history = [] if history is None else list(history)10821083 if content is None or isinstance(content, bytes):1084 self.is_closed = True1085 self.is_stream_consumed = True1086 self._raw_content = content or b""1087 else:1088 self.is_closed = False1089 self.is_stream_consumed = False1090 self._raw_stream = content10911092 def read(self) -> bytes:1093 """1094 Read and return the response content.1095 """1096 if not hasattr(self, "_content"):1097 self._content = b"".join([part for part in self.stream()])1098 return self._content10991100 def stream(self) -> typing.Iterator[bytes]:1101 """1102 A byte-iterator over the decoded response content.1103 This allows us to handle gzip, deflate, and brotli encoded responses.1104 """1105 if hasattr(self, "_content"):1106 yield self._content1107 else:1108 for chunk in self.raw():1109 yield self.decoder.decode(chunk)1110 yield self.decoder.flush()11111112 def stream_text(self) -> typing.Iterator[str]:1113 """1114 A str-iterator over the decoded response content1115 that handles both gzip, deflate, etc but also detects the content's1116 string encoding.1117 """1118 decoder = TextDecoder(encoding=self.charset_encoding)1119 for chunk in self.stream():1120 yield decoder.decode(chunk)1121 yield decoder.flush()11221123 def raw(self) -> typing.Iterator[bytes]:1124 """1125 A byte-iterator over the raw response content.1126 """1127 if hasattr(self, "_raw_content"):1128 yield self._raw_content1129 else:1130 if self.is_stream_consumed:1131 raise StreamConsumed()1132 if self.is_closed:1133 raise ResponseClosed()11341135 self.is_stream_consumed = True1136 for part in self._raw_stream:1137 yield part1138 self.close()11391140 def close(self) -> None:1141 """1142 Close the response and release the connection.1143 Automatically called if the response body is read to completion.1144 """1145 if not self.is_closed:1146 self.is_closed = True1147 if self.on_close is not None:1148 self.on_close()11491150969class Cookies(MutableMapping):970 """971 HTTP Cookies, as a mutable mapping.972 """
10 unmodified lines
983 self.jar.set_cookie(cookie)984 else:985 self.jar = cookies9861169 def extract_cookies(self, response: BaseResponse) -> None:987 def extract_cookies(self, response: Response) -> None:988 """989 Loads any cookies based on the response `Set-Cookie` headers.990 """991 assert response.request is not None
1 unmodified line
993 urllib_request = self._CookieCompatRequest(response.request)994995 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore9961179 def set_cookie_header(self, request: BaseRequest) -> None:997 def set_cookie_header(self, request: Request) -> None:998 """999 Sets an appropriate 'Cookie:' HTTP header on the `Request`.1000 """1001 urllib_request = self._CookieCompatRequest(request)
110 unmodified lines
1112 Wraps a `Request` instance up in a compatibility interface suitable1113 for use with `CookieJar` operations.1114 """11151298 def __init__(self, request: BaseRequest) -> None:1116 def __init__(self, request: Request) -> None:1117 super().__init__(1118 url=str(request.url),1119 headers=dict(request.headers),1120 method=request.method,
9 unmodified lines
1130 Wraps a `Request` instance up in a compatibility interface suitable1131 for use with `CookieJar` operations.1132 """11331316 def __init__(self, response: BaseResponse):1134 def __init__(self, response: Response):1135 self.response = response11361137 def info(self) -> email.message.Message:1138 info = email.message.Message()
3 unmodified lines
modified:tests/client/test_async_client.py+16 added-16 removed
5 unmodified lines
678async def test_get(server, backend):9 url = server.url10 async with httpx.AsyncClient(backend=backend) as client:10 async with httpx.Client(backend=backend) as client:11 response = await client.get(url)12 assert response.status_code == 20013 assert response.text == "Hello, world!"14 assert response.http_version == "HTTP/1.1"
4 unmodified lines
1920async def test_build_request(server, backend):21 url = server.url.copy_with(path="/echo_headers")22 headers = {"Custom-header": "value"}23 async with httpx.AsyncClient(backend=backend) as client:23 async with httpx.Client(backend=backend) as client:24 request = client.build_request("GET", url)25 request.headers.update(headers)26 response = await client.send(request)27
8 unmodified lines
36 """37 Verify that the client is capable of making a simple request if not given a backend.38 """39 url = server.url40 async with httpx.AsyncClient() as client:40 async with httpx.Client() as client:41 response = await client.get(url)42 assert response.status_code == 20043 assert response.text == "Hello, world!"44 assert response.http_version == "HTTP/1.1"
2 unmodified lines
474849async def test_post(server, backend):50 url = server.url51 async with httpx.AsyncClient(backend=backend) as client:51 async with httpx.Client(backend=backend) as client:52 response = await client.post(url, data=b"Hello, world!")53 assert response.status_code == 200545556async def test_post_json(server, backend):57 url = server.url58 async with httpx.AsyncClient(backend=backend) as client:58 async with httpx.Client(backend=backend) as client:59 response = await client.post(url, json={"text": "Hello, world!"})60 assert response.status_code == 200616263async def test_stream_response(server, backend):64 async with httpx.AsyncClient(backend=backend) as client:64 async with httpx.Client(backend=backend) as client:65 response = await client.request("GET", server.url, stream=True)66 assert response.status_code == 20067 body = await response.read()68 assert body == b"Hello, world!"69 assert response.content == b"Hello, world!"707172async def test_access_content_stream_response(server, backend):73 async with httpx.AsyncClient(backend=backend) as client:73 async with httpx.Client(backend=backend) as client:74 response = await client.request("GET", server.url, stream=True)75 assert response.status_code == 20076 with pytest.raises(httpx.ResponseNotRead):77 response.content
3 unmodified lines
81 async def hello_world():82 yield b"Hello, "83 yield b"world!"8485 async with httpx.AsyncClient(backend=backend) as client:85 async with httpx.Client(backend=backend) as client:86 response = await client.request("POST", server.url, data=hello_world())87 assert response.status_code == 200888990async def test_raise_for_status(server, backend):91 async with httpx.AsyncClient(backend=backend) as client:91 async with httpx.Client(backend=backend) as client:92 for status_code in (200, 400, 404, 500, 505):93 response = await client.request(94 "GET", server.url.copy_with(path=f"/status/{status_code}")95 )
6 unmodified lines
102 assert response.raise_for_status() is None103104105async def test_options(server, backend):106 async with httpx.AsyncClient(backend=backend) as client:106 async with httpx.Client(backend=backend) as client:107 response = await client.options(server.url)108 assert response.status_code == 200109 assert response.text == "Hello, world!"110111112async def test_head(server, backend):113 async with httpx.AsyncClient(backend=backend) as client:113 async with httpx.Client(backend=backend) as client:114 response = await client.head(server.url)115 assert response.status_code == 200116 assert response.text == ""117118119async def test_put(server, backend):120 async with httpx.AsyncClient(backend=backend) as client:120 async with httpx.Client(backend=backend) as client:121 response = await client.put(server.url, data=b"Hello, world!")122 assert response.status_code == 200123124125async def test_patch(server, backend):126 async with httpx.AsyncClient(backend=backend) as client:126 async with httpx.Client(backend=backend) as client:127 response = await client.patch(server.url, data=b"Hello, world!")128 assert response.status_code == 200129130131async def test_delete(server, backend):132 async with httpx.AsyncClient(backend=backend) as client:132 async with httpx.Client(backend=backend) as client:133 response = await client.delete(server.url)134 assert response.status_code == 200135 assert response.text == "Hello, world!"136
1 unmodified line
138async def test_100_continue(server, backend):139 headers = {"Expect": "100-continue"}140 data = b"Echo request body"141142 async with httpx.AsyncClient(backend=backend) as client:142 async with httpx.Client(backend=backend) as client:143 response = await client.post(144 server.url.copy_with(path="/echo_body"), headers=headers, data=data145 )146
4 unmodified lines
151async def test_uds(uds_server, backend):152 url = uds_server.url153 uds = uds_server.config.uds154 assert uds is not None155 async with httpx.AsyncClient(backend=backend, uds=uds) as client:155 async with httpx.Client(backend=backend, uds=uds) as client:156 response = await client.get(url)157 assert response.status_code == 200158 assert response.text == "Hello, world!"159 assert response.encoding == "iso-8859-1"
modified:tests/client/test_auth.py+88 added-76 removed
4 unmodified lines
5import pytest67from httpx import (8 URL,9 AsyncDispatcher,10 AsyncRequest,11 AsyncResponse,9 CertTypes,10 Client,11 DigestAuth,12 Dispatcher,13 ProtocolError,14 Request,15 Response,16 TimeoutTypes,17 VerifyTypes,18)192021class MockDispatch(AsyncDispatcher):21class MockDispatch(Dispatcher):22 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:23 self.auth_header = auth_header24 self.status_code = status_code2526 async def send(27 self,28 request: AsyncRequest,28 request: Request,29 verify: VerifyTypes = None,30 cert: CertTypes = None,31 timeout: TimeoutTypes = None,32 ) -> AsyncResponse:32 ) -> Response:33 headers = [("www-authenticate", self.auth_header)] if self.auth_header else []34 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()35 return AsyncResponse(35 return Response(36 self.status_code, headers=headers, content=body, request=request37 )383940class MockDigestAuthDispatch(AsyncDispatcher):40class MockDigestAuthDispatch(Dispatcher):41 def __init__(42 self,43 algorithm: str = "SHA-256",44 send_response_after_attempt: int = 1,
7 unmodified lines
52 self._response_count = 05354 async def send(55 self,56 request: AsyncRequest,56 request: Request,57 verify: VerifyTypes = None,58 cert: CertTypes = None,59 timeout: TimeoutTypes = None,60 ) -> AsyncResponse:60 ) -> Response:61 if self._response_count < self.send_response_after_attempt:62 return self.challenge_send(request)6364 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()65 return AsyncResponse(200, content=body, request=request)65 return Response(200, content=body, request=request)6667 def challenge_send(self, request: AsyncRequest) -> AsyncResponse:67 def challenge_send(self, request: Request) -> Response:68 self._response_count += 169 nonce = (70 hashlib.sha256(os.urandom(8)).hexdigest()71 if self._regenerate_nonce
16 unmodified lines
8889 headers = [90 ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)91 ]92 return AsyncResponse(401, headers=headers, content=b"", request=request)92 return Response(401, headers=headers, content=b"", request=request)939495@pytest.mark.asyncio95def test_basic_auth():96async def test_basic_auth():97 url = "https://example.org/"98 auth = ("tomchristie", "password123")9999 with Client(dispatch=MockDispatch()) as client:100 response = client.get(url, auth=auth)100 client = Client(dispatch=MockDispatch())101 response = await client.get(url, auth=auth)102103 assert response.status_code == 200104 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}105106107@pytest.mark.asyncio106def test_basic_auth_in_url():108async def test_basic_auth_in_url():109 url = "https://tomchristie:password123@example.org/"110109 with Client(dispatch=MockDispatch()) as client:110 response = client.get(url)111 client = Client(dispatch=MockDispatch())112 response = await client.get(url)113114 assert response.status_code == 200115 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}116117118@pytest.mark.asyncio116def test_basic_auth_on_session():119async def test_basic_auth_on_session():120 url = "https://example.org/"121 auth = ("tomchristie", "password123")122120 with Client(dispatch=MockDispatch(), auth=auth) as client:121 response = client.get(url)123 client = Client(dispatch=MockDispatch(), auth=auth)124 response = await client.get(url)125126 assert response.status_code == 200127 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}128129130@pytest.mark.asyncio127def test_custom_auth():131async def test_custom_auth():132 url = "https://example.org/"133134 def auth(request):135 request.headers["Authorization"] = "Token 123"136 return request137134 with Client(dispatch=MockDispatch()) as client:135 response = client.get(url, auth=auth)138 client = Client(dispatch=MockDispatch())139 response = await client.get(url, auth=auth)140141 assert response.status_code == 200142 assert response.json() == {"auth": "Token 123"}143144145@pytest.mark.asyncio141def test_netrc_auth():146async def test_netrc_auth():147 os.environ["NETRC"] = "tests/.netrc"148 url = "http://netrcexample.org"149145 with Client(dispatch=MockDispatch()) as client:146 response = client.get(url)150 client = Client(dispatch=MockDispatch())151 response = await client.get(url)152153 assert response.status_code == 200154 assert response.json() == {155 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"156 }157158159@pytest.mark.asyncio154def test_trust_env_auth():160async def test_trust_env_auth():161 os.environ["NETRC"] = "tests/.netrc"162 url = "http://netrcexample.org"163158 with Client(dispatch=MockDispatch()) as client:159 response = client.get(url, trust_env=False)164 client = Client(dispatch=MockDispatch())165 response = await client.get(url, trust_env=False)166167 assert response.status_code == 200168 assert response.json() == {"auth": None}169164 with Client(dispatch=MockDispatch(), trust_env=False) as client:165 response = client.get(url, trust_env=True)170 client = Client(dispatch=MockDispatch(), trust_env=False)171 response = await client.get(url, trust_env=True)172173 assert response.status_code == 200174 assert response.json() == {175 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"
6 unmodified lines
182 assert url == URL(url)183 assert expected == repr(URL(url))184185186@pytest.mark.asyncio180def test_auth_hidden_header():187async def test_auth_hidden_header():188 url = "https://example.org/"189 auth = ("example-username", "example-password")190184 with Client(dispatch=MockDispatch()) as client:185 response = client.get(url, auth=auth)191 client = Client(dispatch=MockDispatch())192 response = await client.get(url, auth=auth)193194 assert "'authorization': '[secure]'" in str(response.request.headers)195196197@pytest.mark.asyncio190def test_auth_invalid_type():198async def test_auth_invalid_type():199 url = "https://example.org/"192 with Client(dispatch=MockDispatch(), auth="not a tuple, not a callable") as client:193 with pytest.raises(TypeError):194 client.get(url)200 client = Client(dispatch=MockDispatch(), auth="not a tuple, not a callable")201 with pytest.raises(TypeError):202 await client.get(url)203204205@pytest.mark.asyncio197def test_digest_auth_returns_no_auth_if_no_digest_header_in_response():206async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response():207 url = "https://example.org/"208 auth = DigestAuth(username="tomchristie", password="password123")209201 with Client(dispatch=MockDispatch()) as client:202 response = client.get(url, auth=auth)210 client = Client(dispatch=MockDispatch())211 response = await client.get(url, auth=auth)212213 assert response.status_code == 200214 assert response.json() == {"auth": None}215216208def test_digest_auth_200_response_including_digest_auth_header_is_returned_as_is():217@pytest.mark.asyncio218async def test_digest_auth_200_response_including_digest_auth_header():219 url = "https://example.org/"220 auth = DigestAuth(username="tomchristie", password="password123")221 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'222213 with Client(214 dispatch=MockDispatch(auth_header=auth_header, status_code=200)215 ) as client:216 response = client.get(url, auth=auth)223 client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=200))224 response = await client.get(url, auth=auth)225226 assert response.status_code == 200227 assert response.json() == {"auth": None}228229222def test_digest_auth_401_response_without_digest_auth_header_is_returned_as_is():230@pytest.mark.asyncio231async def test_digest_auth_401_response_without_digest_auth_header():232 url = "https://example.org/"233 auth = DigestAuth(username="tomchristie", password="password123")234226 with Client(dispatch=MockDispatch(auth_header="", status_code=401)) as client:227 response = client.get(url, auth=auth)235 client = Client(dispatch=MockDispatch(auth_header="", status_code=401))236 response = await client.get(url, auth=auth)237238 assert response.status_code == 401239 assert response.json() == {"auth": None}240
10 unmodified lines
251 ("SHA-512", 64, 128),252 ("SHA-512-SESS", 64, 128),253 ],254)255@pytest.mark.asyncio246def test_digest_auth(algorithm, expected_hash_length, expected_response_length):256async def test_digest_auth(algorithm, expected_hash_length, expected_response_length):257 url = "https://example.org/"258 auth = DigestAuth(username="tomchristie", password="password123")259250 with Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm)) as client:251 response = client.get(url, auth=auth)260 client = Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm))261 response = await client.get(url, auth=auth)262263 assert response.status_code == 200264 auth = response.json()["auth"]265 assert auth.startswith("Digest ")
12 unmodified lines
278 assert digest_data["nc"] == "00000001"279 assert len(digest_data["cnonce"]) == 16 + 2280281282@pytest.mark.asyncio272def test_digest_auth_no_specified_qop():283async def test_digest_auth_no_specified_qop():284 url = "https://example.org/"285 auth = DigestAuth(username="tomchristie", password="password123")286276 with Client(dispatch=MockDigestAuthDispatch(qop=None)) as client:277 response = client.get(url, auth=auth)287 client = Client(dispatch=MockDigestAuthDispatch(qop=None))288 response = await client.get(url, auth=auth)289290 assert response.status_code == 200291 auth = response.json()["auth"]292 assert auth.startswith("Digest ")
13 unmodified lines
306 assert digest_data["algorithm"] == "SHA-256"307308309@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))310@pytest.mark.asyncio299def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str):311async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str):312 url = "https://example.org/"313 auth = DigestAuth(username="tomchristie", password="password123")314303 with Client(dispatch=MockDigestAuthDispatch(qop=qop)) as client:304 client.get(url, auth=auth)315 client = Client(dispatch=MockDigestAuthDispatch(qop=qop))316 await client.get(url, auth=auth)317318319@pytest.mark.asyncio307def test_digest_auth_qop_auth_int_not_implemented():320async def test_digest_auth_qop_auth_int_not_implemented():321 url = "https://example.org/"322 auth = DigestAuth(username="tomchristie", password="password123")323 client = Client(dispatch=MockDigestAuthDispatch(qop="auth-int"))324325 with pytest.raises(NotImplementedError):312 with Client(dispatch=MockDigestAuthDispatch(qop="auth-int")) as client:313 client.get(url, auth=auth)326 await client.get(url, auth=auth)327328329@pytest.mark.asyncio316def test_digest_auth_qop_must_be_auth_or_auth_int():330async def test_digest_auth_qop_must_be_auth_or_auth_int():331 url = "https://example.org/"332 auth = DigestAuth(username="tomchristie", password="password123")333 client = Client(dispatch=MockDigestAuthDispatch(qop="not-auth"))334335 with pytest.raises(ProtocolError):321 with Client(dispatch=MockDigestAuthDispatch(qop="not-auth")) as client:322 client.get(url, auth=auth)336 await client.get(url, auth=auth)337338339@pytest.mark.asyncio325def test_digest_auth_incorrect_credentials():340async def test_digest_auth_incorrect_credentials():341 url = "https://example.org/"342 auth = DigestAuth(username="tomchristie", password="password123")343329 with Client(330 dispatch=MockDigestAuthDispatch(send_response_after_attempt=2)331 ) as client:332 response = client.get(url, auth=auth)344 client = Client(dispatch=MockDigestAuthDispatch(send_response_after_attempt=2))345 response = await client.get(url, auth=auth)346347 assert response.status_code == 401348349
6 unmodified lines
356 'qop="auth,auth-int",nonce="abc",opaque="xyz"',357 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list358 ],359)360@pytest.mark.asyncio347def test_digest_auth_raises_protocol_error_on_malformed_header(auth_header: str):361async def test_digest_auth_raises_protocol_error_on_malformed_header(auth_header: str):362 url = "https://example.org/"363 auth = DigestAuth(username="tomchristie", password="password123")364 client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=401))365366 with pytest.raises(ProtocolError):352 with Client(353 dispatch=MockDispatch(auth_header=auth_header, status_code=401)354 ) as client:355 client.get(url, auth=auth)367 await client.get(url, auth=auth)
modified:tests/client/test_client.py+74 added-73 removed
4 unmodified lines
56import httpx789@pytest.mark.asyncio9def test_get(server):10async def test_get(server):11 url = server.url11 with httpx.Client() as http:12 response = http.get(url)12 async with httpx.Client() as http:13 response = await http.get(url)14 assert response.status_code == 20015 assert response.url == url16 assert response.content == b"Hello, world!"17 assert response.text == "Hello, world!"
5 unmodified lines
23 assert repr(response) == "<Response [200 OK]>"24 assert response.elapsed > timedelta(0)252627@pytest.mark.asyncio26def test_build_request(server):28async def test_build_request(server):29 url = server.url.copy_with(path="/echo_headers")30 headers = {"Custom-header": "value"}3130 with httpx.Client() as http:31 request = http.build_request("GET", url)32 async with httpx.Client() as client:33 request = client.build_request("GET", url)34 request.headers.update(headers)33 response = http.send(request)35 response = await client.send(request)3637 assert response.status_code == 20038 assert response.url == url3940 assert response.json()["Custom-header"] == "value"414243@pytest.mark.asyncio41def test_post(server):42 with httpx.Client() as http:43 response = http.post(server.url, data=b"Hello, world!")44async def test_post(server):45 async with httpx.Client() as client:46 response = await client.post(server.url, data=b"Hello, world!")47 assert response.status_code == 20048 assert response.reason_phrase == "OK"495051@pytest.mark.asyncio48def test_post_json(server):49 with httpx.Client() as http:50 response = http.post(server.url, json={"text": "Hello, world!"})52async def test_post_json(server):53 async with httpx.Client() as client:54 response = await client.post(server.url, json={"text": "Hello, world!"})55 assert response.status_code == 20056 assert response.reason_phrase == "OK"575859@pytest.mark.asyncio55def test_stream_response(server):56 with httpx.Client() as http:57 response = http.get(server.url, stream=True)60async def test_stream_response(server):61 async with httpx.Client() as client:62 response = await client.get(server.url, stream=True)63 assert response.status_code == 20059 content = response.read()64 content = await response.read()65 assert content == b"Hello, world!"666768@pytest.mark.asyncio63def test_stream_iterator(server):64 with httpx.Client() as http:65 response = http.get(server.url, stream=True)69async def test_stream_iterator(server):70 async with httpx.Client() as client:71 response = await client.get(server.url, stream=True)72 assert response.status_code == 20073 body = b""68 for chunk in response.stream():74 async for chunk in response.stream():75 body += chunk76 assert body == b"Hello, world!"777879@pytest.mark.asyncio73def test_raw_iterator(server):74 with httpx.Client() as http:75 response = http.get(server.url, stream=True)80async def test_raw_iterator(server):81 async with httpx.Client() as client:82 response = await client.get(server.url, stream=True)83 assert response.status_code == 20084 body = b""78 for chunk in response.raw():85 async for chunk in response.raw():86 body += chunk87 assert body == b"Hello, world!"81 response.close() # TODO: should Response be available as context managers?88 await response.close()899091@pytest.mark.asyncio84def test_raise_for_status(server):85 with httpx.Client() as client:92async def test_raise_for_status(server):93 async with httpx.Client() as client:94 for status_code in (200, 400, 404, 500, 505):87 response = client.request(95 response = await client.request(96 "GET", server.url.copy_with(path="/status/{}".format(status_code))97 )98 if 400 <= status_code < 600:99 with pytest.raises(httpx.HTTPError) as exc_info:
2 unmodified lines
102 else:103 assert response.raise_for_status() is None104105106@pytest.mark.asyncio98def test_options(server):99 with httpx.Client() as http:100 response = http.options(server.url)107async def test_options(server):108 async with httpx.Client() as client:109 response = await client.options(server.url)110 assert response.status_code == 200111 assert response.reason_phrase == "OK"112113114@pytest.mark.asyncio105def test_head(server):106 with httpx.Client() as http:107 response = http.head(server.url)115async def test_head(server):116 async with httpx.Client() as client:117 response = await client.head(server.url)118 assert response.status_code == 200119 assert response.reason_phrase == "OK"120121122@pytest.mark.asyncio112def test_put(server):113 with httpx.Client() as http:114 response = http.put(server.url, data=b"Hello, world!")123async def test_put(server):124 async with httpx.Client() as client:125 response = await client.put(server.url, data=b"Hello, world!")126 assert response.status_code == 200127 assert response.reason_phrase == "OK"128129130@pytest.mark.asyncio119def test_patch(server):120 with httpx.Client() as http:121 response = http.patch(server.url, data=b"Hello, world!")131async def test_patch(server):132 async with httpx.Client() as client:133 response = await client.patch(server.url, data=b"Hello, world!")134 assert response.status_code == 200135 assert response.reason_phrase == "OK"136137138@pytest.mark.asyncio126def test_delete(server):127 with httpx.Client() as http:128 response = http.delete(server.url)139async def test_delete(server):140 async with httpx.Client() as client:141 response = await client.delete(server.url)142 assert response.status_code == 200143 assert response.reason_phrase == "OK"144145146@pytest.mark.asyncio133def test_base_url(server):147async def test_base_url(server):148 base_url = server.url135 with httpx.Client(base_url=base_url) as http:136 response = http.get("/")149 async with httpx.Client(base_url=base_url) as client:150 response = await client.get("/")151 assert response.status_code == 200152 assert response.url == base_url153154155@pytest.mark.asyncio141def test_uds(uds_server):156async def test_uds(uds_server):157 url = uds_server.url158 uds = uds_server.config.uds159 assert uds is not None145 with httpx.Client(uds=uds) as http:146 response = http.get(url)160 async with httpx.Client(uds=uds) as client:161 response = await client.get(url)162 assert response.status_code == 200163 assert response.text == "Hello, world!"164 assert response.encoding == "iso-8859-1"165
5 unmodified lines
171 assert url.scheme == "https"172 assert url.is_ssl173174160class DerivedFromAsyncioBackend(httpx.AsyncioBackend):161 pass162163164class AnyBackend:165 pass166167168def test_client_backend_must_be_asyncio_based():169 httpx.Client(backend=httpx.AsyncioBackend())170 httpx.Client(backend=DerivedFromAsyncioBackend())171172 with pytest.raises(ValueError):173 httpx.Client(backend=AnyBackend())174175176def test_elapsed_delay(server):177 with httpx.Client() as http:178 response = http.get(server.url.copy_with(path="/slow_response/100"))175@pytest.mark.asyncio176async def test_elapsed_delay(server):177 async with httpx.Client() as client:178 response = await client.get(server.url.copy_with(path="/slow_response/100"))179 assert response.elapsed.total_seconds() == pytest.approx(0.1, rel=0.2)180181182def test_elapsed_delay_ignores_read_time(server):183 with httpx.Client() as http:184 response = http.get(182@pytest.mark.asyncio183async def test_elapsed_delay_ignores_read_time(server):184 async with httpx.Client() as client:185 response = await client.get(186 server.url.copy_with(path="/slow_response/100"), stream=True187 )188 sleep(0.2)188 response.read()189 await response.read()190 assert response.elapsed.total_seconds() == pytest.approx(0.1, rel=0.2)
modified:tests/client/test_cookies.py+45 added-36 removed
1import json2from http.cookiejar import Cookie, CookieJar34import pytest56from httpx import (5 AsyncDispatcher,6 AsyncRequest,7 AsyncResponse,7 CertTypes,8 Client,9 Cookies,10 Dispatcher,11 Request,12 Response,13 TimeoutTypes,14 VerifyTypes,15)161716class MockDispatch(AsyncDispatcher):18class MockDispatch(Dispatcher):19 async def send(20 self,19 request: AsyncRequest,21 request: Request,22 verify: VerifyTypes = None,23 cert: CertTypes = None,24 timeout: TimeoutTypes = None,23 ) -> AsyncResponse:25 ) -> Response:26 if request.url.path.startswith("/echo_cookies"):27 body = json.dumps({"cookies": request.headers.get("Cookie")}).encode()26 return AsyncResponse(200, content=body, request=request)28 return Response(200, content=body, request=request)29 elif request.url.path.startswith("/set_cookie"):30 headers = {"set-cookie": "example-name=example-value"}29 return AsyncResponse(200, headers=headers, request=request)31 return Response(200, headers=headers, request=request)323334@pytest.mark.asyncio32def test_set_cookie():35async def test_set_cookie():36 """37 Send a request including a cookie.38 """39 url = "http://example.org/echo_cookies"40 cookies = {"example-name": "example-value"}4139 with Client(dispatch=MockDispatch()) as client:40 response = client.get(url, cookies=cookies)42 client = Client(dispatch=MockDispatch())43 response = await client.get(url, cookies=cookies)4445 assert response.status_code == 20046 assert response.json() == {"cookies": "example-name=example-value"}474849@pytest.mark.asyncio46def test_set_cookie_with_cookiejar():50async def test_set_cookie_with_cookiejar():51 """52 Send a request including a cookie, using a `CookieJar` instance.53 """54
19 unmodified lines
74 rfc2109=False,75 )76 cookies.set_cookie(cookie)7774 with Client(dispatch=MockDispatch()) as client:75 response = client.get(url, cookies=cookies)78 client = Client(dispatch=MockDispatch())79 response = await client.get(url, cookies=cookies)8081 assert response.status_code == 20082 assert response.json() == {"cookies": "example-name=example-value"}838485@pytest.mark.asyncio81def test_setting_client_cookies_to_cookiejar():86async def test_setting_client_cookies_to_cookiejar():87 """88 Send a request including a cookie, using a `CookieJar` instance.89 """90
19 unmodified lines
110 rfc2109=False,111 )112 cookies.set_cookie(cookie)113109 with Client(dispatch=MockDispatch()) as client:110 client.cookies = cookies111 response = client.get(url)114 client = Client(dispatch=MockDispatch())115 client.cookies = cookies116 response = await client.get(url)117118 assert response.status_code == 200119 assert response.json() == {"cookies": "example-name=example-value"}120121122@pytest.mark.asyncio117def test_set_cookie_with_cookies_model():123async def test_set_cookie_with_cookies_model():124 """125 Send a request including a cookie, using a `Cookies` instance.126 """127128 url = "http://example.org/echo_cookies"129 cookies = Cookies()130 cookies["example-name"] = "example-value"131126 with Client(dispatch=MockDispatch()) as client:127 response = client.get(url, cookies=cookies)132 client = Client(dispatch=MockDispatch())133 response = await client.get(url, cookies=cookies)134135 assert response.status_code == 200136 assert response.json() == {"cookies": "example-name=example-value"}137138139@pytest.mark.asyncio133def test_get_cookie():140async def test_get_cookie():141 url = "http://example.org/set_cookie"142136 with Client(dispatch=MockDispatch()) as client:137 response = client.get(url)143 client = Client(dispatch=MockDispatch())144 response = await client.get(url)145146 assert response.status_code == 200147 assert response.cookies["example-name"] == "example-value"148 assert client.cookies["example-name"] == "example-value"149150151@pytest.mark.asyncio144def test_cookie_persistence():152async def test_cookie_persistence():153 """154 Ensure that Client instances persist cookies between requests.155 """148 with Client(dispatch=MockDispatch()) as client:149 response = client.get("http://example.org/echo_cookies")150 assert response.status_code == 200151 assert response.json() == {"cookies": None}156 client = Client(dispatch=MockDispatch())157153 response = client.get("http://example.org/set_cookie")154 assert response.status_code == 200155 assert response.cookies["example-name"] == "example-value"156 assert client.cookies["example-name"] == "example-value"158 response = await client.get("http://example.org/echo_cookies")159 assert response.status_code == 200160 assert response.json() == {"cookies": None}161158 response = client.get("http://example.org/echo_cookies")159 assert response.status_code == 200160 assert response.json() == {"cookies": "example-name=example-value"}162 response = await client.get("http://example.org/set_cookie")163 assert response.status_code == 200164 assert response.cookies["example-name"] == "example-value"165 assert client.cookies["example-name"] == "example-value"166167 response = await client.get("http://example.org/echo_cookies")168 assert response.status_code == 200169 assert response.json() == {"cookies": "example-name=example-value"}
modified:tests/client/test_headers.py+31 added-26 removed
3 unmodified lines
45import pytest67from httpx import (8 AsyncDispatcher,9 AsyncRequest,10 AsyncResponse,8 CertTypes,9 Client,10 Dispatcher,11 Request,12 Response,13 TimeoutTypes,14 VerifyTypes,15 __version__,16 models,17)181920class MockDispatch(AsyncDispatcher):20class MockDispatch(Dispatcher):21 async def send(22 self,23 request: AsyncRequest,23 request: Request,24 verify: VerifyTypes = None,25 cert: CertTypes = None,26 timeout: TimeoutTypes = None,27 ) -> AsyncResponse:27 ) -> Response:28 if request.url.path.startswith("/echo_headers"):29 request_headers = dict(request.headers.items())30 body = json.dumps({"headers": request_headers}).encode()31 return AsyncResponse(200, content=body, request=request)31 return Response(200, content=body, request=request)323334@pytest.mark.asyncio34def test_client_header():35async def test_client_header():36 """37 Set a header in the Client.38 """39 url = "http://example.org/echo_headers"40 headers = {"Example-Header": "example-value"}4141 with Client(dispatch=MockDispatch(), headers=headers) as client:42 response = client.get(url)42 client = Client(dispatch=MockDispatch(), headers=headers)43 response = await client.get(url)4445 assert response.status_code == 20046 assert response.json() == {47 "headers": {
6 unmodified lines
54 }55 }565758@pytest.mark.asyncio57def test_header_merge():59async def test_header_merge():60 url = "http://example.org/echo_headers"61 client_headers = {"User-Agent": "python-myclient/0.2.1"}62 request_headers = {"X-Auth-Token": "FooBarBazToken"}61 with Client(dispatch=MockDispatch(), headers=client_headers) as client:62 response = client.get(url, headers=request_headers)63 client = Client(dispatch=MockDispatch(), headers=client_headers)64 response = await client.get(url, headers=request_headers)6566 assert response.status_code == 20067 assert response.json() == {68 "headers": {
6 unmodified lines
75 }76 }777879@pytest.mark.asyncio77def test_header_merge_conflicting_headers():80async def test_header_merge_conflicting_headers():81 url = "http://example.org/echo_headers"82 client_headers = {"X-Auth-Token": "FooBar"}83 request_headers = {"X-Auth-Token": "BazToken"}81 with Client(dispatch=MockDispatch(), headers=client_headers) as client:82 response = client.get(url, headers=request_headers)84 client = Client(dispatch=MockDispatch(), headers=client_headers)85 response = await client.get(url, headers=request_headers)8687 assert response.status_code == 20088 assert response.json() == {89 "headers": {
6 unmodified lines
96 }97 }9899100@pytest.mark.asyncio97def test_header_update():101async def test_header_update():102 url = "http://example.org/echo_headers"99 with Client(dispatch=MockDispatch()) as client:100 first_response = client.get(url)101 client.headers.update(102 {"User-Agent": "python-myclient/0.2.1", "Another-Header": "AThing"}103 )104 second_response = client.get(url)103 client = Client(dispatch=MockDispatch())104 first_response = await client.get(url)105 client.headers.update(106 {"User-Agent": "python-myclient/0.2.1", "Another-Header": "AThing"}107 )108 second_response = await client.get(url)109110 assert first_response.status_code == 200111 assert first_response.json() == {112 "headers": {
23 unmodified lines
136 with pytest.raises(KeyError):137 del headers["baz"]138139140@pytest.mark.asyncio136def test_host_without_auth_in_header():141async def test_host_without_auth_in_header():142 url = "http://username:password@example.org:80/echo_headers"143139 with Client(dispatch=MockDispatch()) as client:140 response = client.get(url)144 client = Client(dispatch=MockDispatch())145 response = await client.get(url)146147 assert response.status_code == 200148 assert response.json() == {149 "headers": {
8 unmodified lines
modified:tests/client/test_proxies.py+4 added-4 removed
28 unmodified lines
29 assert len(expected_proxies) == len(client.proxies)303132def test_proxies_has_same_properties_as_dispatch():33 client = httpx.AsyncClient(33 client = httpx.Client(34 proxies="http://127.0.0.1",35 verify="/path/to/verify",36 cert="/path/to/cert",37 trust_env=False,
62 unmodified lines
100 ),101 ],102)103def test_dispatcher_for_request(url, proxies, expected):104 client = httpx.AsyncClient(proxies=proxies)105 request = httpx.AsyncRequest("GET", url)104 client = httpx.Client(proxies=proxies)105 request = httpx.Request("GET", url)106 dispatcher = client._dispatcher_for_request(request, client.proxies)107108 if expected is None:109 assert isinstance(dispatcher, httpx.ConnectionPool)
4 unmodified lines
114115116def test_unsupported_proxy_scheme():117 with pytest.raises(ValueError):118 httpx.AsyncClient(proxies="ftp://127.0.0.1")118 httpx.Client(proxies="ftp://127.0.0.1")
modified:tests/client/test_queryparams.py+13 added-10 removed
1import json23import pytest45from httpx import (4 AsyncDispatcher,5 AsyncRequest,6 AsyncResponse,6 CertTypes,7 Client,8 Dispatcher,9 QueryParams,10 Request,11 Response,12 TimeoutTypes,13 VerifyTypes,14)15from httpx.models import URL161716class MockDispatch(AsyncDispatcher):18class MockDispatch(Dispatcher):19 async def send(20 self,19 request: AsyncRequest,21 request: Request,22 verify: VerifyTypes = None,23 cert: CertTypes = None,24 timeout: TimeoutTypes = None,23 ) -> AsyncResponse:25 ) -> Response:26 if request.url.path.startswith("/echo_queryparams"):27 body = json.dumps({"ok": "ok"}).encode()26 return AsyncResponse(200, content=body, request=request)28 return Response(200, content=body, request=request)293031def test_client_queryparams():32 client = Client(params={"a": "b"})
11 unmodified lines
44 assert isinstance(client.params, QueryParams)45 assert client.params["a"] == "b"464748@pytest.mark.asyncio46def test_client_queryparams_echo():49async def test_client_queryparams_echo():50 url = "http://example.org/echo_queryparams"51 client_queryparams = "first=str"52 request_queryparams = {"second": "dict"}50 with Client(dispatch=MockDispatch(), params=client_queryparams) as client:51 response = client.get(url, params=request_queryparams)53 client = Client(dispatch=MockDispatch(), params=client_queryparams)54 response = await client.get(url, params=request_queryparams)5556 assert response.status_code == 20057 assert response.url == URL(58 "http://example.org/echo_queryparams?first=str&second=dict"
1 unmodified line
modified:tests/client/test_redirects.py+49 added-53 removed
3 unmodified lines
4import pytest56from httpx import (7 URL,8 AsyncClient,9 AsyncDispatcher,10 AsyncRequest,11 AsyncResponse,8 CertTypes,9 Client,10 Dispatcher,11 NotRedirectResponse,12 RedirectBodyUnavailable,13 RedirectLoop,14 Request,15 Response,16 TimeoutTypes,17 TooManyRedirects,18 VerifyTypes,19 codes,20)212223class MockDispatch(AsyncDispatcher):23class MockDispatch(Dispatcher):24 async def send(25 self,26 request: AsyncRequest,26 request: Request,27 verify: VerifyTypes = None,28 cert: CertTypes = None,29 timeout: TimeoutTypes = None,30 ) -> AsyncResponse:30 ) -> Response:31 if request.url.path == "/no_redirect":32 return AsyncResponse(codes.OK, request=request)32 return Response(codes.OK, request=request)3334 elif request.url.path == "/redirect_301":35 status_code = codes.MOVED_PERMANENTLY36 headers = {"location": "https://example.org/"}37 return AsyncResponse(status_code, headers=headers, request=request)37 return Response(status_code, headers=headers, request=request)3839 elif request.url.path == "/redirect_302":40 status_code = codes.FOUND41 headers = {"location": "https://example.org/"}42 return AsyncResponse(status_code, headers=headers, request=request)42 return Response(status_code, headers=headers, request=request)4344 elif request.url.path == "/redirect_303":45 status_code = codes.SEE_OTHER46 headers = {"location": "https://example.org/"}47 return AsyncResponse(status_code, headers=headers, request=request)47 return Response(status_code, headers=headers, request=request)4849 elif request.url.path == "/relative_redirect":50 headers = {"location": "/"}51 return AsyncResponse(codes.SEE_OTHER, headers=headers, request=request)51 return Response(codes.SEE_OTHER, headers=headers, request=request)5253 elif request.url.path == "/no_scheme_redirect":54 headers = {"location": "//example.org/"}55 return AsyncResponse(codes.SEE_OTHER, headers=headers, request=request)55 return Response(codes.SEE_OTHER, headers=headers, request=request)5657 elif request.url.path == "/multiple_redirects":58 params = parse_qs(request.url.query)59 count = int(params.get("count", "0")[0])
2 unmodified lines
62 location = "/multiple_redirects"63 if redirect_count:64 location += "?count=" + str(redirect_count)65 headers = {"location": location} if count else {}66 return AsyncResponse(code, headers=headers, request=request)66 return Response(code, headers=headers, request=request)6768 if request.url.path == "/redirect_loop":69 headers = {"location": "/redirect_loop"}70 return AsyncResponse(codes.SEE_OTHER, headers=headers, request=request)70 return Response(codes.SEE_OTHER, headers=headers, request=request)7172 elif request.url.path == "/cross_domain":73 headers = {"location": "https://example.org/cross_domain_target"}74 return AsyncResponse(codes.SEE_OTHER, headers=headers, request=request)74 return Response(codes.SEE_OTHER, headers=headers, request=request)7576 elif request.url.path == "/cross_domain_target":77 headers = dict(request.headers.items())78 content = json.dumps({"headers": headers}).encode()79 return AsyncResponse(codes.OK, content=content, request=request)79 return Response(codes.OK, content=content, request=request)8081 elif request.url.path == "/redirect_body":82 await request.read()83 headers = {"location": "/redirect_body_target"}84 return AsyncResponse(85 codes.PERMANENT_REDIRECT, headers=headers, request=request86 )84 return Response(codes.PERMANENT_REDIRECT, headers=headers, request=request)8586 elif request.url.path == "/redirect_no_body":87 await request.read()88 headers = {"location": "/redirect_body_target"}91 return AsyncResponse(codes.SEE_OTHER, headers=headers, request=request)89 return Response(codes.SEE_OTHER, headers=headers, request=request)9091 elif request.url.path == "/redirect_body_target":92 content = await request.read()93 headers = dict(request.headers.items())94 body = json.dumps({"body": content.decode(), "headers": headers}).encode()97 return AsyncResponse(codes.OK, content=body, request=request)95 return Response(codes.OK, content=body, request=request)9697 elif request.url.path == "/cross_subdomain":98 if request.headers["host"] != "www.example.org":99 headers = {"location": "https://www.example.org/cross_subdomain"}102 return AsyncResponse(100 return Response(101 codes.PERMANENT_REDIRECT, headers=headers, request=request102 )103 else:106 return AsyncResponse(107 codes.OK, content=b"Hello, world!", request=request108 )104 return Response(codes.OK, content=b"Hello, world!", request=request)105110 return AsyncResponse(codes.OK, content=b"Hello, world!", request=request)106 return Response(codes.OK, content=b"Hello, world!", request=request)107108109async def test_no_redirect(backend):114 client = AsyncClient(dispatch=MockDispatch(), backend=backend)110 client = Client(dispatch=MockDispatch(), backend=backend)111 url = "https://example.com/no_redirect"112 response = await client.get(url)113 assert response.status_code == 200114 with pytest.raises(NotRedirectResponse):115 await response.next()116117118async def test_redirect_301(backend):123 client = AsyncClient(dispatch=MockDispatch(), backend=backend)119 client = Client(dispatch=MockDispatch(), backend=backend)120 response = await client.post("https://example.org/redirect_301")121 assert response.status_code == codes.OK122 assert response.url == URL("https://example.org/")123 assert len(response.history) == 1124125126async def test_redirect_302(backend):131 client = AsyncClient(dispatch=MockDispatch(), backend=backend)127 client = Client(dispatch=MockDispatch(), backend=backend)128 response = await client.post("https://example.org/redirect_302")129 assert response.status_code == codes.OK130 assert response.url == URL("https://example.org/")131 assert len(response.history) == 1132133134async def test_redirect_303(backend):139 client = AsyncClient(dispatch=MockDispatch(), backend=backend)135 client = Client(dispatch=MockDispatch(), backend=backend)136 response = await client.get("https://example.org/redirect_303")137 assert response.status_code == codes.OK138 assert response.url == URL("https://example.org/")139 assert len(response.history) == 1140141142async def test_disallow_redirects(backend):147 client = AsyncClient(dispatch=MockDispatch(), backend=backend)143 client = Client(dispatch=MockDispatch(), backend=backend)144 response = await client.post(145 "https://example.org/redirect_303", allow_redirects=False146 )147 assert response.status_code == codes.SEE_OTHER
8 unmodified lines
156 assert len(response.history) == 1157158159async def test_relative_redirect(backend):164 client = AsyncClient(dispatch=MockDispatch(), backend=backend)160 client = Client(dispatch=MockDispatch(), backend=backend)161 response = await client.get("https://example.org/relative_redirect")162 assert response.status_code == codes.OK163 assert response.url == URL("https://example.org/")164 assert len(response.history) == 1165166167async def test_no_scheme_redirect(backend):172 client = AsyncClient(dispatch=MockDispatch(), backend=backend)168 client = Client(dispatch=MockDispatch(), backend=backend)169 response = await client.get("https://example.org/no_scheme_redirect")170 assert response.status_code == codes.OK171 assert response.url == URL("https://example.org/")172 assert len(response.history) == 1173174175async def test_fragment_redirect(backend):180 client = AsyncClient(dispatch=MockDispatch(), backend=backend)176 client = Client(dispatch=MockDispatch(), backend=backend)177 response = await client.get("https://example.org/relative_redirect#fragment")178 assert response.status_code == codes.OK179 assert response.url == URL("https://example.org/#fragment")180 assert len(response.history) == 1181182183async def test_multiple_redirects(backend):188 client = AsyncClient(dispatch=MockDispatch(), backend=backend)184 client = Client(dispatch=MockDispatch(), backend=backend)185 response = await client.get("https://example.org/multiple_redirects?count=20")186 assert response.status_code == codes.OK187 assert response.url == URL("https://example.org/multiple_redirects")188 assert len(response.history) == 20
7 unmodified lines
196 assert len(response.history[1].history) == 1197198199async def test_too_many_redirects(backend):204 client = AsyncClient(dispatch=MockDispatch(), backend=backend)200 client = Client(dispatch=MockDispatch(), backend=backend)201 with pytest.raises(TooManyRedirects):202 await client.get("https://example.org/multiple_redirects?count=21")203204205async def test_too_many_redirects_calling_next(backend):210 client = AsyncClient(dispatch=MockDispatch(), backend=backend)206 client = Client(dispatch=MockDispatch(), backend=backend)207 url = "https://example.org/multiple_redirects?count=21"208 response = await client.get(url, allow_redirects=False)209 with pytest.raises(TooManyRedirects):210 while response.is_redirect:211 response = await response.next()212213214async def test_redirect_loop(backend):219 client = AsyncClient(dispatch=MockDispatch(), backend=backend)215 client = Client(dispatch=MockDispatch(), backend=backend)216 with pytest.raises(RedirectLoop):217 await client.get("https://example.org/redirect_loop")218219220async def test_redirect_loop_calling_next(backend):225 client = AsyncClient(dispatch=MockDispatch(), backend=backend)221 client = Client(dispatch=MockDispatch(), backend=backend)222 url = "https://example.org/redirect_loop"223 response = await client.get(url, allow_redirects=False)224 with pytest.raises(RedirectLoop):225 while response.is_redirect:226 response = await response.next()227228229async def test_cross_domain_redirect(backend):234 client = AsyncClient(dispatch=MockDispatch(), backend=backend)230 client = Client(dispatch=MockDispatch(), backend=backend)231 url = "https://example.com/cross_domain"232 headers = {"Authorization": "abc"}233 response = await client.get(url, headers=headers)234 assert response.url == URL("https://example.org/cross_domain_target")235 assert "authorization" not in response.json()["headers"]236237238async def test_same_domain_redirect(backend):243 client = AsyncClient(dispatch=MockDispatch(), backend=backend)239 client = Client(dispatch=MockDispatch(), backend=backend)240 url = "https://example.org/cross_domain"241 headers = {"Authorization": "abc"}242 response = await client.get(url, headers=headers)243 assert response.url == URL("https://example.org/cross_domain_target")
3 unmodified lines
247async def test_body_redirect(backend):248 """249 A 308 redirect should preserve the request body.250 """255 client = AsyncClient(dispatch=MockDispatch(), backend=backend)251 client = Client(dispatch=MockDispatch(), backend=backend)252 url = "https://example.org/redirect_body"253 data = b"Example request body"254 response = await client.post(url, data=data)255 assert response.url == URL("https://example.org/redirect_body_target")
4 unmodified lines
260async def test_no_body_redirect(backend):261 """262 A 303 redirect should remove the request body.263 """268 client = AsyncClient(dispatch=MockDispatch(), backend=backend)264 client = Client(dispatch=MockDispatch(), backend=backend)265 url = "https://example.org/redirect_no_body"266 data = b"Example request body"267 response = await client.post(url, data=data)268 assert response.url == URL("https://example.org/redirect_body_target")
1 unmodified line
270 assert "content-length" not in response.json()["headers"]271272273async def test_cannot_redirect_streaming_body(backend):278 client = AsyncClient(dispatch=MockDispatch(), backend=backend)274 client = Client(dispatch=MockDispatch(), backend=backend)275 url = "https://example.org/redirect_body"276277 async def streaming_body():278 yield b"Example request body"
2 unmodified lines
281 await client.post(url, data=streaming_body())282283284async def test_cross_subdomain_redirect(backend):289 client = AsyncClient(dispatch=MockDispatch(), backend=backend)285 client = Client(dispatch=MockDispatch(), backend=backend)286 url = "https://example.com/cross_subdomain"287 response = await client.get(url)288 assert response.url == URL("https://www.example.org/cross_subdomain")289290295class MockCookieDispatch(AsyncDispatcher):291class MockCookieDispatch(Dispatcher):292 async def send(293 self,298 request: AsyncRequest,294 request: Request,295 verify: VerifyTypes = None,296 cert: CertTypes = None,297 timeout: TimeoutTypes = None,302 ) -> AsyncResponse:298 ) -> Response:299 if request.url.path == "/":300 if "cookie" in request.headers:301 content = b"Logged in"302 else:303 content = b"Not logged in"308 return AsyncResponse(codes.OK, content=content, request=request)304 return Response(codes.OK, content=content, request=request)305306 elif request.url.path == "/login":307 status_code = codes.SEE_OTHER308 headers = {
3 unmodified lines
312 "httponly; samesite=lax"313 ),314 }315320 return AsyncResponse(status_code, headers=headers, request=request)316 return Response(status_code, headers=headers, request=request)317318 elif request.url.path == "/logout":319 status_code = codes.SEE_OTHER320 headers = {
2 unmodified lines
323 "session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; "324 "httponly; samesite=lax"325 ),326 }331 return AsyncResponse(status_code, headers=headers, request=request)327 return Response(status_code, headers=headers, request=request)328329330async def test_redirect_cookie_behavior(backend):335 client = AsyncClient(dispatch=MockCookieDispatch(), backend=backend)331 client = Client(dispatch=MockCookieDispatch(), backend=backend)332333 # The client is not logged in.334 response = await client.get("https://example.com/")335 assert response.url == "https://example.com/"
21 unmodified lines
modified:tests/dispatch/test_http2.py+18 added-88 removed
4 unmodified lines
5import h2.events6import pytest7from h2.settings import SettingCodes89from httpx import AsyncClient, Client, Response, Timeout9from httpx import Client, Response, Timeout1011from .utils import MockHTTP2Backend1213
8 unmodified lines
22 headers = {"Content-Length": str(len(content))}23 return Response(200, headers=headers, content=content)242526@pytest.mark.asyncio26def test_http2_get_request():27async def test_http2_get_request():28 backend = MockHTTP2Backend(app=app)2929 with Client(backend=backend) as client:30 response = client.get("http://example.org")3132 assert response.status_code == 20033 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}343536async def test_async_http2_get_request(backend):37 backend = MockHTTP2Backend(app=app, backend=backend)3839 async with AsyncClient(backend=backend) as client:30 async with Client(backend=backend) as client:31 response = await client.get("http://example.org")3233 assert response.status_code == 20034 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}353637@pytest.mark.asyncio46def test_http2_post_request():38async def test_http2_post_request():39 backend = MockHTTP2Backend(app=app)4049 with Client(backend=backend) as client:50 response = client.post("http://example.org", data=b"<data>")5152 assert response.status_code == 20053 assert json.loads(response.content) == {54 "method": "POST",55 "path": "/",56 "body": "<data>",57 }585960async def test_async_http2_post_request(backend):61 backend = MockHTTP2Backend(app=app, backend=backend)6263 async with AsyncClient(backend=backend) as client:41 async with Client(backend=backend) as client:42 response = await client.post("http://example.org", data=b"<data>")4344 assert response.status_code == 20045 assert json.loads(response.content) == {
2 unmodified lines
48 "body": "<data>",49 }505152@pytest.mark.asyncio74def test_http2_large_post_request():53async def test_http2_large_post_request():54 backend = MockHTTP2Backend(app=app)5556 data = b"a" * 10000078 with Client(backend=backend) as client:79 response = client.post("http://example.org", data=data)80 assert response.status_code == 20081 assert json.loads(response.content) == {82 "method": "POST",83 "path": "/",84 "body": data.decode(),85 }868788async def test_async_http2_large_post_request(backend):89 backend = MockHTTP2Backend(app=app, backend=backend)9091 data = b"a" * 10000092 async with AsyncClient(backend=backend) as client:57 async with Client(backend=backend) as client:58 response = await client.post("http://example.org", data=data)59 assert response.status_code == 20060 assert json.loads(response.content) == {61 "method": "POST",
1 unmodified line
63 "body": data.decode(),64 }656667@pytest.mark.asyncio102def test_http2_multiple_requests():68async def test_http2_multiple_requests():69 backend = MockHTTP2Backend(app=app)70105 with Client(backend=backend) as client:106 response_1 = client.get("http://example.org/1")107 response_2 = client.get("http://example.org/2")108 response_3 = client.get("http://example.org/3")109110 assert response_1.status_code == 200111 assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}112113 assert response_2.status_code == 200114 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}115116 assert response_3.status_code == 200117 assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}118119120async def test_async_http2_multiple_requests(backend):121 backend = MockHTTP2Backend(app=app, backend=backend)122123 async with AsyncClient(backend=backend) as client:71 async with Client(backend=backend) as client:72 response_1 = await client.get("http://example.org/1")73 response_2 = await client.get("http://example.org/2")74 response_3 = await client.get("http://example.org/3")75
6 unmodified lines
82 assert response_3.status_code == 20083 assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}848586@pytest.mark.asyncio138def test_http2_reconnect():87async def test_http2_reconnect():88 """89 If a connection has been dropped between requests, then we should90 be seemlessly reconnected.91 """92 backend = MockHTTP2Backend(app=app)93145 with Client(backend=backend) as client:146 response_1 = client.get("http://example.org/1")147 backend.server.close_connection = True148 response_2 = client.get("http://example.org/2")149150 assert response_1.status_code == 200151 assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}152153 assert response_2.status_code == 200154 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}155156157async def test_async_http2_reconnect(backend):158 """159 If a connection has been dropped between requests, then we should160 be seemlessly reconnected.161 """162 backend = MockHTTP2Backend(app=app, backend=backend)163164 async with AsyncClient(backend=backend) as client:94 async with Client(backend=backend) as client:95 response_1 = await client.get("http://example.org/1")96 backend.server.close_connection = True97 response_2 = await client.get("http://example.org/2")98
6 unmodified lines
105106async def test_http2_settings_in_handshake(backend):107 backend = MockHTTP2Backend(app=app, backend=backend)108179 async with AsyncClient(backend=backend) as client:109 async with Client(backend=backend) as client:110 await client.get("http://example.org")111112 h2_conn = backend.server.conn113
24 unmodified lines
138 assert changed_setting.new_value == expected_settings[setting_code]139140141async def test_http2_live_request(backend):212 async with AsyncClient(backend=backend) as client:142 async with Client(backend=backend) as client:143 try:144 resp = await client.get("https://nghttp2.org/httpbin/anything")145 except Timeout:146 pytest.xfail(reason="nghttp2.org appears to be unresponsive")
4 unmodified lines
deleted:tests/dispatch/test_threaded.py-112 removed
1import json23from httpx import (4 AsyncClient,5 CertTypes,6 Client,7 Dispatcher,8 Request,9 Response,10 TimeoutTypes,11 VerifyTypes,12)131415def streaming_body():16 for part in [b"Hello", b", ", b"world!"]:17 yield part181920class MockDispatch(Dispatcher):21 def send(22 self,23 request: Request,24 verify: VerifyTypes = None,25 cert: CertTypes = None,26 timeout: TimeoutTypes = None,27 ) -> Response:28 if request.url.path == "/streaming_response":29 return Response(200, content=streaming_body(), request=request)30 elif request.url.path == "/echo_request_body":31 content = request.read()32 return Response(200, content=content, request=request)33 elif request.url.path == "/echo_request_body_streaming":34 content = b"".join([part for part in request.stream()])35 return Response(200, content=content, request=request)36 else:37 body = json.dumps({"hello": "world"}).encode()38 return Response(200, content=body, request=request)394041def test_threaded_dispatch():42 """43 Use a synchronous 'Dispatcher' class with the client.44 Calls to the dispatcher will end up running within a thread pool.45 """46 url = "https://example.org/"47 with Client(dispatch=MockDispatch()) as client:48 response = client.get(url)4950 assert response.status_code == 20051 assert response.json() == {"hello": "world"}525354async def test_async_threaded_dispatch(backend):55 """56 Use a synchronous 'Dispatcher' class with the async client.57 Calls to the dispatcher will end up running within a thread pool.58 """59 url = "https://example.org/"60 async with AsyncClient(dispatch=MockDispatch(), backend=backend) as client:61 response = await client.get(url)6263 assert response.status_code == 20064 assert response.json() == {"hello": "world"}656667def test_threaded_streaming_response():68 url = "https://example.org/streaming_response"69 with Client(dispatch=MockDispatch()) as client:70 response = client.get(url)7172 assert response.status_code == 20073 assert response.text == "Hello, world!"747576def test_threaded_streaming_request():77 url = "https://example.org/echo_request_body"78 with Client(dispatch=MockDispatch()) as client:79 response = client.post(url, data=streaming_body())8081 assert response.status_code == 20082 assert response.text == "Hello, world!"838485def test_threaded_request_body():86 url = "https://example.org/echo_request_body"87 with Client(dispatch=MockDispatch()) as client:88 response = client.post(url, data=b"Hello, world!")8990 assert response.status_code == 20091 assert response.text == "Hello, world!"929394def test_threaded_request_body_streaming():95 url = "https://example.org/echo_request_body_streaming"96 with Client(dispatch=MockDispatch()) as client:97 response = client.post(url, data=b"Hello, world!")9899 assert response.status_code == 200100 assert response.text == "Hello, world!"101102103def test_dispatch_class():104 """105 Use a synchronous 'Dispatcher' class directly.106 """107 url = "https://example.org/"108 with MockDispatch() as dispatcher:109 response = dispatcher.request("GET", url)110111 assert response.status_code == 200112 assert response.json() == {"hello": "world"}
modified:tests/models/test_requests.py+8 added-10 removed
17 unmodified lines
18 assert request.headers["Content-Length"] == "8"192021def test_url_encoded_data():22 for RequestClass in (httpx.Request, httpx.AsyncRequest):23 request = RequestClass("POST", "http://example.org", data={"test": "123"})24 assert request.headers["Content-Type"] == "application/x-www-form-urlencoded"25 assert request.content == b"test=123"22 request = httpx.Request("POST", "http://example.org", data={"test": "123"})23 assert request.headers["Content-Type"] == "application/x-www-form-urlencoded"24 assert request.content == b"test=123"252627def test_json_encoded_data():29 for RequestClass in (httpx.Request, httpx.AsyncRequest):30 request = RequestClass("POST", "http://example.org", json={"test": 123})31 assert request.headers["Content-Type"] == "application/json"32 assert request.content == b'{"test": 123}'28 request = httpx.Request("POST", "http://example.org", json={"test": 123})29 assert request.headers["Content-Type"] == "application/json"30 assert request.content == b'{"test": 123}'313233def test_transfer_encoding_header():36 def streaming_body(data):34 async def streaming_body(data):35 yield data # pragma: nocover3637 data = streaming_body(b"test 123")38
16 unmodified lines
55 assert request.headers["Accept-Encoding"] == "identity"565758def test_override_content_length_header():61 def streaming_body(data):59 async def streaming_body(data):60 yield data # pragma: nocover6162 data = streaming_body(b"test 123")63 headers = {"Content-Length": "8"}
25 unmodified lines
modified:tests/models/test_responses.py+22 added-76 removed
113 unmodified lines
114 assert response.text == "Snowman: â\x98\x83"115 assert response.encoding == "iso-8859-1"116117118@pytest.mark.asyncio118def test_read_response():119async def test_read_response():120 response = httpx.Response(200, content=b"Hello, world!")121122 assert response.status_code == 200123 assert response.text == "Hello, world!"124 assert response.encoding == "ascii"125 assert response.is_closed126126 content = response.read()127 content = await response.read()128129 assert content == b"Hello, world!"130 assert response.content == b"Hello, world!"131 assert response.is_closed132133134@pytest.mark.asyncio133def test_raw_interface():135async def test_raw_interface():136 response = httpx.Response(200, content=b"Hello, world!")137138 raw = b""137 for part in response.raw():139 async for part in response.raw():140 raw += part141 assert raw == b"Hello, world!"142143144@pytest.mark.asyncio142def test_stream_interface():145async def test_stream_interface():146 response = httpx.Response(200, content=b"Hello, world!")147148 content = b""146 for part in response.stream():147 content += part148 assert content == b"Hello, world!"149150151@pytest.mark.asyncio152async def test_async_stream_interface():153 response = httpx.AsyncResponse(200, content=b"Hello, world!")154155 content = b""149 async for part in response.stream():150 content += part151 assert content == b"Hello, world!"152153161def test_stream_interface_after_read():154@pytest.mark.asyncio155async def test_stream_text():156 response = httpx.Response(200, content=b"Hello, world!")157164 response.read()158 await response.read()159166 content = b""167 for part in response.stream():160 content = ""161 async for part in response.stream_text():162 content += part169 assert content == b"Hello, world!"163 assert content == "Hello, world!"164165166@pytest.mark.asyncio173async def test_async_stream_interface_after_read():174 response = httpx.AsyncResponse(200, content=b"Hello, world!")167async def test_stream_interface_after_read():168 response = httpx.Response(200, content=b"Hello, world!")169170 await response.read()171172 content = b""
1 unmodified line
174 content += part175 assert content == b"Hello, world!"176177184def test_streaming_response():185 response = httpx.Response(200, content=streaming_body())186187 assert response.status_code == 200188 assert not response.is_closed189190 content = response.read()191192 assert content == b"Hello, world!"193 assert response.content == b"Hello, world!"194 assert response.is_closed195196178@pytest.mark.asyncio198async def test_async_streaming_response():199 response = httpx.AsyncResponse(200, content=async_streaming_body())179async def test_streaming_response():180 response = httpx.Response(200, content=async_streaming_body())181182 assert response.status_code == 200183 assert not response.is_closed184
3 unmodified lines
188 assert response.content == b"Hello, world!"189 assert response.is_closed190191211def test_cannot_read_after_stream_consumed():212 response = httpx.Response(200, content=streaming_body())213214 content = b""215 for part in response.stream():216 content += part217218 with pytest.raises(httpx.StreamConsumed):219 response.read()220221192@pytest.mark.asyncio223async def test_async_cannot_read_after_stream_consumed():224 response = httpx.AsyncResponse(200, content=async_streaming_body())193async def test_cannot_read_after_stream_consumed():194 response = httpx.Response(200, content=async_streaming_body())195196 content = b""197 async for part in response.stream():198 content += part
1 unmodified line
200 with pytest.raises(httpx.StreamConsumed):201 await response.read()202203234def test_cannot_read_after_response_closed():235 response = httpx.Response(200, content=streaming_body())236237 response.close()238239 with pytest.raises(httpx.ResponseClosed):240 response.read()241242204@pytest.mark.asyncio244async def test_async_cannot_read_after_response_closed():245 response = httpx.AsyncResponse(200, content=async_streaming_body())205async def test_cannot_read_after_response_closed():206 response = httpx.Response(200, content=async_streaming_body())207208 await response.close()209210 with pytest.raises(httpx.ResponseClosed):
60 unmodified lines
271)272def test_link_headers(headers, expected):273 response = httpx.Response(200, content=None, headers=headers)274 assert response.links == expected314315316@pytest.mark.asyncio317async def test_stream_text():318 async def iterator():319 yield b"Hello, world!"320321 response = httpx.AsyncResponse(200, content=iterator().__aiter__())322323 await response.read()324325 content = ""326 async for part in response.stream_text():327 content += part328 assert content == "Hello, world!"
deleted:tests/requests_compat/__init__.py
deleted:tests/requests_compat/conftest.py-17 removed
1import sys23import pytest45import httpx678def pytest_configure(config):9 # Allow to 'import requests' without having to write 'import httpx as requests'.10 # This means we *could* literally copy-paste Requests test code as-is, if relevant.11 sys.modules["requests"] = httpx121314@pytest.fixture(autouse=True)15def patch_httpx(monkeypatch):16 """Monkey-patch Requests APIs onto HTTPX."""17 monkeypatch.setattr(httpx, "session", httpx.Client, raising=False)
deleted:tests/requests_compat/test_api.py-29 removed
1"""Test compatibility with the Requests high-level API."""2import pytest3import requests456@pytest.mark.copied_from(7 "https://github.com/psf/requests/blob/v2.22.0/tests/test_requests.py#L61-L70"8)9def test_entrypoints():10 requests.session11 requests.session().get12 requests.session().head13 requests.get14 requests.head15 requests.put16 requests.patch17 requests.post181920@pytest.mark.copied_from(21 "https://github.com/psf/requests/blob/v2.22.0/tests/test_requests.py#L72",22 changes=["added noqa comment to silence flake8"],23)24@pytest.mark.xfail(25 reason="PoolManager has no obvious equivalent in HTTPX", raises=ImportError26)27def test_poolmanager_entrypoint():28 # Not really an entry point, but people rely on it.29 from requests.packages.urllib3.poolmanager import PoolManager # noqa: F401
modified:tests/conftest.py+1 added-5 removed
161 unmodified lines
162163164async def redirect_301(scope, receive, send):165 await send(166 {167 "type": "http.response.start",168 "status": 301,169 "headers": [[b"location", b"/"]],170 }166 {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}167 )168 await send({"type": "http.response.body"})169170
166 unmodified lines
modified:tests/test_api.py+28 added-19 removed
1 unmodified line
23import httpx456@pytest.mark.asyncio6def test_get(server):7 response = httpx.get(server.url)7async def test_get(server):8 response = await httpx.get(server.url)9 assert response.status_code == 20010 assert response.reason_phrase == "OK"11 assert response.text == "Hello, world!"12 assert response.http_version == "HTTP/1.1"131415@pytest.mark.asyncio14def test_post(server):15 response = httpx.post(server.url, data=b"Hello, world!")16async def test_post(server):17 response = await httpx.post(server.url, data=b"Hello, world!")18 assert response.status_code == 20019 assert response.reason_phrase == "OK"202122@pytest.mark.asyncio20def test_post_byte_iterator(server):21 def data():23async def test_post_byte_iterator(server):24 async def data():25 yield b"Hello"26 yield b", "27 yield b"world!"2826 response = httpx.post(server.url, data=data())29 response = await httpx.post(server.url, data=data())30 assert response.status_code == 20031 assert response.reason_phrase == "OK"323334@pytest.mark.asyncio31def test_options(server):32 response = httpx.options(server.url)35async def test_options(server):36 response = await httpx.options(server.url)37 assert response.status_code == 20038 assert response.reason_phrase == "OK"394041@pytest.mark.asyncio37def test_head(server):38 response = httpx.head(server.url)42async def test_head(server):43 response = await httpx.head(server.url)44 assert response.status_code == 20045 assert response.reason_phrase == "OK"464748@pytest.mark.asyncio43def test_put(server):44 response = httpx.put(server.url, data=b"Hello, world!")49async def test_put(server):50 response = await httpx.put(server.url, data=b"Hello, world!")51 assert response.status_code == 20052 assert response.reason_phrase == "OK"535455@pytest.mark.asyncio49def test_patch(server):50 response = httpx.patch(server.url, data=b"Hello, world!")56async def test_patch(server):57 response = await httpx.patch(server.url, data=b"Hello, world!")58 assert response.status_code == 20059 assert response.reason_phrase == "OK"606162@pytest.mark.asyncio55def test_delete(server):56 response = httpx.delete(server.url)63async def test_delete(server):64 response = await httpx.delete(server.url)65 assert response.status_code == 20066 assert response.reason_phrase == "OK"676869@pytest.mark.asyncio61def test_get_invalid_url(server):70async def test_get_invalid_url(server):71 with pytest.raises(httpx.InvalidURL):63 httpx.get("invalid://example.org")72 await httpx.get("invalid://example.org")
modified:tests/test_asgi.py+8 added-30 removed
37 unmodified lines
38 await send({"type": "http.response.body", "body": output})39 raise ValueError()404142@pytest.mark.asyncio42def test_asgi():43async def test_asgi():44 client = httpx.Client(app=hello_world)44 response = client.get("http://www.example.org/")45 assert response.status_code == 20046 assert response.text == "Hello, World!"474849async def test_asgi_async(backend):50 client = httpx.AsyncClient(app=hello_world, backend=backend)45 response = await client.get("http://www.example.org/")46 assert response.status_code == 20047 assert response.text == "Hello, World!"484950@pytest.mark.asyncio56def test_asgi_upload():51async def test_asgi_upload():52 client = httpx.Client(app=echo_body)58 response = client.post("http://www.example.org/", data=b"example")59 assert response.status_code == 20060 assert response.text == "example"616263async def test_asgi_upload_async(backend):64 client = httpx.AsyncClient(app=echo_body, backend=backend)53 response = await client.post("http://www.example.org/", data=b"example")54 assert response.status_code == 20055 assert response.text == "example"565758@pytest.mark.asyncio70def test_asgi_exc():59async def test_asgi_exc():60 client = httpx.Client(app=raise_exc)61 with pytest.raises(ValueError):73 client.get("http://www.example.org/")747576async def test_asgi_exc_async(backend):77 client = httpx.AsyncClient(app=raise_exc, backend=backend)78 with pytest.raises(ValueError):62 await client.get("http://www.example.org/")636465@pytest.mark.asyncio82def test_asgi_exc_after_response():66async def test_asgi_exc_after_response():67 client = httpx.Client(app=raise_exc_after_response)68 with pytest.raises(ValueError):85 client.get("http://www.example.org/")868788async def test_asgi_exc_after_response_async(backend):89 client = httpx.AsyncClient(app=raise_exc_after_response, backend=backend)90 with pytest.raises(ValueError):69 await client.get("http://www.example.org/")
modified:tests/test_decoders.py+15 added-11 removed
69 unmodified lines
70 response = httpx.Response(200, headers=headers, content=compressed_body)71 assert response.content == body727374@pytest.mark.asyncio74def test_streaming():75async def test_streaming():76 body = b"test 123"77 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)7878 def compress(body):79 async def compress(body):80 yield compressor.compress(body)81 yield compressor.flush()8283 headers = [(b"Content-Encoding", b"gzip")]84 response = httpx.Response(200, headers=headers, content=compress(body))85 assert not hasattr(response, "body")85 assert response.read() == body86 assert await response.read() == body878889@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))90def test_empty_content(header_value):
37 unmodified lines
128 "euc-jp",129 ),130 ],131)132@pytest.mark.asyncio131def test_text_decoder(data, encoding):132 def iterator():133async def test_text_decoder(data, encoding):134 async def iterator():135 nonlocal data136 for chunk in data:137 yield chunk138139 response = httpx.Response(200, content=iterator())140 await response.read()138 assert "".join(response.stream_text()) == (b"".join(data)).decode(encoding)141 assert response.text == (b"".join(data)).decode(encoding)142143144@pytest.mark.asyncio141def test_text_decoder_known_encoding():142 def iterator():145async def test_text_decoder_known_encoding():146 async def iterator():147 yield b"\x83g"148 yield b"\x83"149 yield b"\x89\x83x\x83\x8b"150
2 unmodified lines
153 headers=[(b"Content-Type", b"text/html; charset=shift-jis")],154 content=iterator(),155 )156157 await response.read()153 assert "".join(response.stream_text()) == "トラベル"158 assert "".join(response.text) == "トラベル"159160161def test_text_decoder_empty_cases():162 decoder = TextDecoder()
8 unmodified lines
171 headers = [(b"Content-Encoding", b"invalid-header")]172 body = b"test 123"173174 response = httpx.Response(200, headers=headers, content=body)170171 assert response.read() == body175 assert response.content == body
modified:tests/test_multipart.py+15 added-10 removed
18 unmodified lines
19)202122class MockDispatch(Dispatcher):23 def send(23 async def send(24 self,25 request: Request,26 verify: VerifyTypes = None,27 cert: CertTypes = None,28 timeout: TimeoutTypes = None,29 http_versions: HTTPVersionTypes = None,30 ) -> Response:31 content = await request.read()31 return Response(200, content=request.read())32 return Response(200, content=content)333435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))36@pytest.mark.asyncio35def test_multipart(value, output):37async def test_multipart(value, output):38 client = Client(dispatch=MockDispatch())3940 # Test with a single-value 'data' argument, and a plain file 'files' argument.41 data = {"text": value}42 files = {"file": io.BytesIO(b"<file content>")}41 response = client.post("http://127.0.0.1:8000/", data=data, files=files)43 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)44 assert response.status_code == 2004546 # We're using the cgi module to verify the behavior here, which is a47 # bit grungy, but sufficient just for our testing purposes.
8 unmodified lines
56 assert multipart["file"] == [b"<file content>"]575859@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))60@pytest.mark.asyncio58def test_multipart_invalid_key(key):61async def test_multipart_invalid_key(key):62 client = Client(dispatch=MockDispatch())63 data = {key: "abc"}64 files = {"file": io.BytesIO(b"<file content>")}65 with pytest.raises(TypeError) as e:63 client.post("http://127.0.0.1:8000/", data=data, files=files)66 await client.post("http://127.0.0.1:8000/", data=data, files=files)67 assert "Invalid type for name" in str(e.value)686970@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))71@pytest.mark.asyncio68def test_multipart_invalid_value(value):72async def test_multipart_invalid_value(value):73 client = Client(dispatch=MockDispatch())74 data = {"text": value}75 files = {"file": io.BytesIO(b"<file content>")}76 with pytest.raises(TypeError) as e:73 client.post("http://127.0.0.1:8000/", data=data, files=files)77 await client.post("http://127.0.0.1:8000/", data=data, files=files)78 assert "Invalid type for value" in str(e.value)798081@pytest.mark.asyncio77def test_multipart_file_tuple():82async def test_multipart_file_tuple():83 client = Client(dispatch=MockDispatch())8485 # Test with a list of values 'data' argument, and a tuple style 'files' argument.86 data = {"text": ["abc"]}87 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}83 response = client.post("http://127.0.0.1:8000/", data=data, files=files)88 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)89 assert response.status_code == 2009091 # We're using the cgi module to verify the behavior here, which is a92 # bit grungy, but sufficient just for our testing purposes.
91 unmodified lines
modified:tests/test_timeouts.py+4 added-15 removed
1import pytest23from httpx import (4 AsyncClient,4 Client,5 ConnectTimeout,6 PoolLimits,7 PoolTimeout,
5 unmodified lines
1314async def test_read_timeout(server, backend):15 timeout = TimeoutConfig(read_timeout=1e-6)1618 async with AsyncClient(timeout=timeout, backend=backend) as client:17 async with Client(timeout=timeout, backend=backend) as client:18 with pytest.raises(ReadTimeout):19 await client.get(server.url.copy_with(path="/slow_response"))202122async def test_write_timeout(server, backend):23 timeout = TimeoutConfig(write_timeout=1e-6)2426 async with AsyncClient(timeout=timeout, backend=backend) as client:25 async with Client(timeout=timeout, backend=backend) as client:26 with pytest.raises(WriteTimeout):27 data = b"*" * 1024 * 1024 * 10028 await client.put(server.url.copy_with(path="/slow_response"), data=data)293031async def test_connect_timeout(server, backend):32 timeout = TimeoutConfig(connect_timeout=1e-6)3335 async with AsyncClient(timeout=timeout, backend=backend) as client:34 async with Client(timeout=timeout, backend=backend) as client:35 with pytest.raises(ConnectTimeout):36 # See https://stackoverflow.com/questions/100841/37 await client.get("http://10.255.255.1/")383940async def test_pool_timeout(server, backend):41 pool_limits = PoolLimits(hard_limit=1, pool_timeout=1e-4)4244 async with AsyncClient(pool_limits=pool_limits, backend=backend) as client:43 async with Client(pool_limits=pool_limits, backend=backend) as client:44 response = await client.get(server.url, stream=True)4546 with pytest.raises(PoolTimeout):47 await client.get("http://localhost:8000/")4849 await response.read()515253def test_sync_infinite_timeout(server):54 """Regression test for a bug that occurred under Python 3.6.5556 See: https://github.com/encode/httpx/issues/38257 """58 no_timeout = TimeoutConfig()59 with Client(timeout=no_timeout) as client:60 client.get(server.url.copy_with(path="/slow_response/50"))
modified:tests/test_utils.py+3 added-3 removed
102 unmodified lines
103104@pytest.mark.asyncio105async def test_logs_debug(server, capsys):106 with override_log_level("debug"):107 async with httpx.AsyncClient() as client:107 async with httpx.Client() as client:108 response = await client.get(server.url)109 assert response.status_code == 200110 stderr = capsys.readouterr().err111 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr
2 unmodified lines
114115@pytest.mark.asyncio116async def test_logs_trace(server, capsys):117 with override_log_level("trace"):118 async with httpx.AsyncClient() as client:118 async with httpx.Client() as client:119 response = await client.get(server.url)120 assert response.status_code == 200121 stderr = capsys.readouterr().err122 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr
2 unmodified lines
125126@pytest.mark.asyncio127async def test_logs_redirect_chain(server, capsys):128 with override_log_level("debug"):129 async with httpx.AsyncClient() as client:129 async with httpx.Client() as client:130 response = await client.get(server.url.copy_with(path="/redirect_301"))131 assert response.status_code == 200132133 stderr = capsys.readouterr().err.strip()
165 unmodified lines
deleted:tests/test_wsgi.py-95 removed
1import sys23import pytest45import httpx678def hello_world(environ, start_response):9 status = "200 OK"10 output = b"Hello, World!"1112 response_headers = [13 ("Content-type", "text/plain"),14 ("Content-Length", str(len(output))),15 ]1617 start_response(status, response_headers)1819 return [output]202122def echo_body(environ, start_response):23 status = "200 OK"24 output = environ["wsgi.input"].read()2526 response_headers = [27 ("Content-type", "text/plain"),28 ("Content-Length", str(len(output))),29 ]3031 start_response(status, response_headers)3233 return [output]343536def echo_body_with_response_stream(environ, start_response):37 status = "200 OK"3839 response_headers = [("Content-Type", "text/plain")]4041 start_response(status, response_headers)4243 def output_generator(f):44 while True:45 output = f.read(2)46 if not output:47 break48 yield output4950 return output_generator(f=environ["wsgi.input"])515253def raise_exc(environ, start_response):54 status = "500 Server Error"55 output = b"Nope!"5657 response_headers = [58 ("Content-type", "text/plain"),59 ("Content-Length", str(len(output))),60 ]6162 try:63 raise ValueError()64 except ValueError:65 exc_info = sys.exc_info()66 start_response(status, response_headers, exc_info=exc_info)6768 return [output]697071def test_wsgi():72 client = httpx.Client(app=hello_world)73 response = client.get("http://www.example.org/")74 assert response.status_code == 20075 assert response.text == "Hello, World!"767778def test_wsgi_upload():79 client = httpx.Client(app=echo_body)80 response = client.post("http://www.example.org/", data=b"example")81 assert response.status_code == 20082 assert response.text == "example"838485def test_wsgi_upload_with_response_stream():86 client = httpx.Client(app=echo_body_with_response_stream)87 response = client.post("http://www.example.org/", data=b"example")88 assert response.status_code == 20089 assert response.text == "example"909192def test_wsgi_exc():93 client = httpx.Client(app=raise_exc)94 with pytest.raises(ValueError):95 client.get("http://www.example.org/")
modified:mkdocs.yml-2 removed
11 unmodified lines
12 - Introduction: 'index.md'13 - QuickStart: 'quickstart.md'14 - Advanced Usage: 'advanced.md'15 - Environment Variables: 'environment_variables.md'16 - Parallel Requests: 'parallel.md'17 - Async Client: 'async.md'16 - Requests Compatibility: 'compatibility.md'17 - Developer Interface: 'api.md'18 - Contributing: 'contributing.md'19
7 unmodified lines
modified:README.md+18 added-10 removed
14 unmodified lines
15 <img src="https://badge.fury.io/py/httpx.svg" alt="Package version">16</a>17</p>1819**Note**: *This project should be considered as an "alpha" release. It is substantially API complete, but there are still some areas that need more work.*19HTTPX is an asynchronous HTTP client, that supports HTTP/2 and HTTP/1.1.2021It can be used in high-performance async web frameworks, using either asyncio22or trio, and is able to support making large numbers of requests concurrently.2324**Note**: *The 0.8 release switched HTTPX into focusing exclusively on the async25client. It is possible that we'll look at re-introducing a sync API at a26later date.*2728---2930Let's get started...3132*The standard Python REPL does not allow top-level async statements.*3334*To run async examples directly you'll probably want to either use `ipython`,35or use Python 3.8 with `python -m asyncio`.*3637```python38>>> import httpx27>>> r = httpx.get('https://www.example.org/')39>>> r = await httpx.get('https://www.example.org/')40>>> r41<Response [200 OK]>42>>> r.status_code43200
8 unmodified lines
52## Features5354HTTPX builds on the well-established usability of `requests`, and gives you:5544* A requests-compatible API.56* A requests-compatible API wherever possible.57* HTTP/2 and HTTP/1.1 support.46* Support for [issuing HTTP requests in parallel](https://www.encode.io/httpx/parallel/). *(Coming soon)*47* Standard synchronous interface, but [with `async`/`await` support if you need it](https://www.encode.io/httpx/async/).48* Ability to [make requests directly to WSGI or ASGI applications](https://www.encode.io/httpx/advanced/#calling-into-python-web-apps).58* Ability to [make requests directly to ASGI applications](https://www.encode.io/httpx/advanced/#calling-into-python-web-apps).59* Strict timeouts everywhere.60* Fully type annotated.61* 100% test coverage.62
8 unmodified lines
71* Automatic Decompression72* Automatic Content Decoding73* Unicode Response Bodies74* Multipart File Uploads65* HTTP(S) Proxy Support *(TODO)*75* HTTP(S) Proxy Support76* Connection Timeouts77* Streaming Downloads78* .netrc Support79* Chunked Requests
13 unmodified lines
93Project documentation is available at [www.encode.io/httpx/](https://www.encode.io/httpx/).9495For a run-through of all the basics, head over to the [QuickStart](https://www.encode.io/httpx/quickstart/).9687For more advanced topics, see the [Advanced Usage](https://www.encode.io/httpx/advanced/) section, or88the specific topics on making [Parallel Requests](https://www.encode.io/httpx/parallel/) or using the89[Async Client](https://www.encode.io/httpx/async/).97For more advanced topics, see the [Advanced Usage](https://www.encode.io/httpx/advanced/) section.9899The [Developer Interface](https://www.encode.io/httpx/api/) provides a comprehensive API reference.100101## Contribute
22 unmodified lines