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
Provenance
- Commit
206c537- Tree
7b55924- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
1c326d5
52 files changed+845 added−2405 removed
modified:docs/advanced.md+88 added-57 removed
12 unmodified lines13 14 The 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:15 16 ```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 line25 26 ```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 lines44 45 ```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 ```54 55 !!! note56 When you provide a parameter at both the client and request levels, one of two things can happen:57- 57+58 - For headers, query parameters and cookies, the values are merged into one.59 - For all other parameters, the request-level value is used.60 61 Additionally, `Client` constructor accepts some parameters that aren't available at the request level.62 63 One particularly useful parameter is `base_url`, which allows you to define a base URL to prepend to all outgoing requests:64 65 ```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.url70 URL('http://httpbin.org/headers')71 ```72 1 unmodified line74 75 ## Calling into Python Web Apps76 77 You can configure an `httpx` client to call directly into a Python web78-application using either the WSGI or ASGI protocol.78+application using either the ASGI protocol.79 80 This is particularly useful for two main use-cases:81 82 * Using `httpx` as a client inside test cases.83 * Mocking out external services during tests or in dev/staging environments.84 85-Here's an example of integrating against a Flask application:85+Let's take this Starlette application as an example:86 87 ```python88-from flask import Flask89-import httpx88+from starlette.applications import Starlette89+from starlette.responses import HTMLResponse90+from starlette.routing import Route91 92 92-app = Flask(__name__)93+async def hello():94+ return HTMLResponse("Hello World!")95 94-@app.route("/")95-def hello():96- return "Hello World!"96 98-with httpx.Client(app=app) as client:99- r = client.get('http://example/')100- assert r.status_code == 200101- assert r.text == "Hello World!"97+app = Starlette(routes=[Route("/", hello)])98 ```99 100+We can make requests directly against the application, like so:101+102+```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+```109+110 For some more complex cases you might need to customize the WSGI or ASGI111 dispatch. This allows you to:112 113 * 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`.116 117 For example:118 119 ```python120 # Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".115-dispatch = httpx.dispatch.WSGIDispatch(app=app, remote_addr="1.2.3.4")116-with httpx.Client(dispatch=dispatch) as client:121+dispatch = httpx.dispatch.ASGIDispatch(app=app, remote_addr="1.2.3.4")122+async with httpx.Client(dispatch=dispatch) as client:123 ...124 ```125 126 ## Build Request1 unmodified line128 You can use `Client.build_request()` to build a request and129 make modifications before sending the request.130 131 ```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 lines144 145 For example:146 147 ```python142-with httpx.Client(http_versions=["HTTP/1.1"]) as h11_client:143- h11_response = h11_client.get("https://myserver.com")148+async with httpx.Client(http_versions=["HTTP/1.1"]) as h11_client:149+ h11_response = await h11_client.get("https://myserver.com")150 145-with httpx.Client(http_versions=["HTTP/2"]) as h2_client:146- h2_response = h2_client.get("https://myserver.com")151+async with httpx.Client(http_versions=["HTTP/2"]) as h2_client:152+ h2_response = await h2_client.get("https://myserver.com")153 ```154 155 ## .netrc Support156 6 unmodified lines163 you should create a new client or restart the interpreter.164 165 As 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 ```169 170 If `NETRC` environment is empty, HTTPX tries to use default files.171 (`~/.netrc`, `~/_netrc`)22 unmodified lines194 ```python195 import httpx196 197 192-with httpx.Client(uds="/var/run/docker.sock") as client:198+async 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 ```202 203 ## HTTP Proxying204 5 unmodified lines210 >>> 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 ```217 218 Proxies can be configured for a specific scheme and host, all schemes of a host,6 unmodified lines225 ... "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 ```236 237 !!! warning11 unmodified lines249 proxy = httpx.HTTPProxy(250 proxy_url="https://127.0.0.1",251 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY252 )247-with httpx.Client(proxies=proxy) as client:253+async 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 ```257 258 !!! note259 23 unmodified lines283 - For a given request:284 285 ```python286 # Using top-level API281-httpx.get('http://example.com/api/v1/example', timeout=5)287+await httpx.get('http://example.com/api/v1/example', timeout=5)288 289 # Or, with a client:284-with httpx.Client() as client:285- client.get("http://example.com/api/v1/example", timeout=5)290+async with httpx.Client() as client:291+ await client.get("http://example.com/api/v1/example", timeout=5)292 ```293 294 - On a client instance, which results in the given `timeout` being used as a default for requests made with this client:295 296 ```python291-with httpx.Client(timeout=5) as client:292- client.get('http://example.com/api/v1/example')297+async with httpx.Client(timeout=5) as client:298+ await client.get('http://example.com/api/v1/example')299 ```300 301 Besides, you can pass timeouts in two forms:302 6 unmodified lines309 read_timeout=10,310 write_timeout=15311 )312 307-resp = httpx.get('http://example.com/api/v1/example', timeout=timeout)313+resp = await httpx.get('http://example.com/api/v1/example', timeout=timeout)314 ```315 316 ### Default timeouts317 6 unmodified lines324 325 ```python326 url = "http://example.com/api/v1/delay/10"327 322-httpx.get(url, timeout=None) # Times out after 5s328+await httpx.get(url, timeout=None) # Times out after 5s329 330 325-with httpx.Client(timeout=None) as client:326- client.get(url) # Does not timeout, returns after 10s331+async with httpx.Client(timeout=None) as client:332+ await client.get(url) # Does not timeout, returns after 10s333 334 335 timeout = httpx.TimeoutConfig(336 connect_timeout=5,337 read_timeout=None,338 write_timeout=5339 )334-httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s340+await httpx.get(url, timeout=timeout) # Does not timeout, returns after 10s341 ```342 343 ## Multipart file encoding344 2 unmodified lines347 name of the payloads as keys and a tuple of elements as values.348 349 ```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 lines371 `applicaction/octet-stream`.372 373 ```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 lines398 399 ```python400 import httpx401 396-r = httpx.get("https://example.org", verify="path/to/client.pem")402+r = await httpx.get("https://example.org", verify="path/to/client.pem")403 ```404 405 ### Making HTTPS requests to a local server406 6 unmodified lines413 1. Tell HTTPX to use the certificates stored in `client.pem`:414 415 ```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 >>> r419 Response <200 OK>420 ```421+422+## Support async environments423+424+### [asyncio](https://docs.python.org/3/library/asyncio.html) (Default)425+426+By default, `AsyncClient` uses `asyncio` to perform asynchronous operations and I/O calls.427+428+### [trio](https://github.com/python-trio/trio)429+430+To make asynchronous requests in `trio` programs, pass a `TrioBackend` to the `AsyncClient`:431+432+```python433+import trio434+import httpx435+from httpx.concurrency.trio import TrioBackend436+437+async def main():438+ async with httpx.AsyncClient(backend=TrioBackend()) as client:439+ ...440+441+trio.run(main)442+```443+444+!!! important445+ `trio` must be installed to import and use the `TrioBackend`.modified:docs/api.md+2 added-2 removed
34 unmodified lines3536373839394041424330 unmodified lines7475767778787980818276 unmodified lines34 unmodified lines## `Client`
::: httpx.Client :docstring: :members: headers cookies params request get head options post put patch delete build_request send close :members: headers cookies params request get head options post put patch delete build_request send close
## `Response`
*An HTTP response.*30 unmodified lineswhat gets sent over the wire.*
```python>>> request = httpx.Request("GET", "https://example.org", headers={'host': 'example.org'})>>> response = client.send(request)>>> response = await client.send(request)```
* `def __init__(method, url, [params], [data], [json], [headers], [cookies])`* `.method` - **str**76 unmodified linesdeleted:docs/async.md-142 removed
1-# Async Client2-3-HTTPX offers a standard synchronous API by default, but also gives you4-the option of an async client if you need it.5-6-Async is a concurrency model that is far more efficient than multi-threading,7-and can provide significant performance benefits and enable the use of8-long-lived network connections such as WebSockets.9-10-If you're working with an async web framework then you'll also want to use an11-async client for sending outgoing HTTP requests.12-13-## Making Async requests14-15-To make asynchronous requests, you'll need an `AsyncClient`.16-17-```python18->>> async with httpx.AsyncClient() as client:19->>> r = await client.get('https://www.example.com/')20->>> r21-<Response [200 OK]>22-```23-24-!!! tip25- Use [IPython](https://ipython.readthedocs.io/en/stable/) to try this code interactively, as it supports executing `async`/`await` expressions in the console.26-27-!!! note28- The `async with` syntax ensures that all active connections are closed on exit.29-30- 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.31-32-## API Differences33-34-If you're using streaming responses then there are a few bits of API that35-use async methods:36-37-```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-```43-44-The async response methods are:45-46-* `.read()`47-* `.stream()`48-* `.raw()`49-* `.close()`50-51-If you're making [parallel requests](parallel.md), then you'll also need to use an async API:52-53-```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-```61-62-The async parallel methods are:63-64-* `.parallel()` *Used as an "async with" context manager.*65-* `.get_response()`66-* `.next_response()`67-68-## Supported async libraries69-70-You can use `AsyncClient` with any of the following async libraries.71-72-!!! 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.74-75-### [asyncio](https://docs.python.org/3/library/asyncio.html) (Default)76-77-By default, `AsyncClient` uses `asyncio` to perform asynchronous operations and I/O calls.78-79-```python80-import asyncio81-import httpx82-83-async def main():84- async with httpx.AsyncClient() as client:85- ...86-87-asyncio.run(main())88-```89-90-### [trio](https://github.com/python-trio/trio)91-92-To make asynchronous requests in `trio` programs, pass a `TrioBackend` to the `AsyncClient`:93-94-```python95-import trio96-import httpx97-from httpx.concurrency.trio import TrioBackend98-99-async def main():100- async with httpx.AsyncClient(backend=TrioBackend()) as client:101- ...102-103-trio.run(main)104-```105-106-!!! important107- `trio` must be installed to import and use the `TrioBackend`.108-109-## FAQ110-111-### When should I use an `AsyncClient`?112-113-You should use an `AsyncClient` whenever you are inside an *async environment*.114-115-In 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)).116-117-For example, this won't work:118-119-```python120-import asyncio121-import httpx122-123-async def main():124- r = httpx.get("https://example.org")125-126-asyncio.run(main())127-```128-129-Instead, you should use an `AsyncClient`:130-131-```python132-import asyncio133-import httpx134-135-async def main():136- async with httpx.AsyncClient() as client:137- r = await client.get("https://example.org")138-139-asyncio.run(main())140-```141-142-If 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
16 unmodified lines171819202122232425262727282930303131323334353 unmodified lines16 unmodified lines
## Advanced Usage
### requests.Session
The HTTPX equivalent of `requests.Session` is `httpx.Client`.
```pythonsession = requests.Session(**kwargs)```
is equivalent tois generally equivalent to
```pythonwith httpx.Client(**kwargs) as client: ...client = httpx.Client(**kwargs)```
More detailed documentation and usage of `Client` can be found in [Advanced Usage](advanced.md).
3 unmodified linesmodified:docs/index.md+22 added-13 removed
22 unmodified lines23 24 <em>A next-generation HTTP client for Python.</em>25 </div>26 27-!!! 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.27+HTTPX is an asynchronous HTTP client, that supports HTTP/2 and HTTP/1.1.28 29+It can be used in high-performance async web frameworks, using either asyncio30+or trio, and is able to support making large numbers of requests concurrently.31+32+!!! 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.36+37 ---38 39 Let's get started...40 41+!!! note42+ The standard Python REPL does not allow top-level async statements.43+44+ To run async examples directly you'll probably want to either use `ipython`,45+ or use Python 3.8 with `python -m asyncio`.46+47 ```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_code53 2006 unmodified lines60 ```61 62 ## Features63 64+HTTPX is a high performance asynchronous HTTP client, that builds on the52-HTTPX builds on the well-established usability of `requests`, and gives you:65+well-established usability of `requests`, and gives you:66 54-* 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 lines82 * 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 Requests1 unmodified line92 ## Documentation93 94 For a run-through of all the basics, head over to the [QuickStart](quickstart.md).95 85-For more advanced topics, see the [Advanced Usage](advanced.md) section, or86-the specific topics on making [Parallel Requests](parallel.md) or using the87-[Async Client](async.md).96+For more advanced topics, see the [Advanced Usage](advanced.md) section.97 98 The [Developer Interface](api.md) provides a comprehensive API reference.99 100 ## Dependencies25 unmodified linesdeleted:docs/parallel.md-70 removed
1-# Parallel Requests2-3-!!! 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.7-8-HTTPX allows you to make HTTP requests in parallel in a highly efficient way,9-using async under the hood, while still presenting a standard threaded interface.10-11-This has the huge benefit of allowing you to efficiently make parallel HTTP12-requests without having to switch out to using async all the way through.13-14-## Making Parallel Requests15-16-Let's make two outgoing HTTP requests in parallel:17-18-```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-```25-26-If we're making lots of outgoing requests, we might not want to deal with the27-responses sequentially, but rather deal with each response that comes back28-as soon as it's available:29-30-```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-```37-38-## Exceptions and Cancellations39-40-The style of using `parallel` blocks ensures that you'll always have a well-defined exception and cancellation behaviors. Request exceptions are only ever41-raised when calling either `get_response` or `next_response` and any pending42-requests are canceled on exiting the block.43-44-## Parallel requests with a Client45-46-You can also call `parallel()` from a client instance, which allows you to47-control the authentication or dispatch behavior for all requests within the48-block.49-50-```python51->>> with httpx.Client() as client:52-... with client.parallel() as parallel:53-... ...54-```55-56-## Async parallel requests57-58-If you're working within an async framework, then you'll want to use a fully59-async API for making requests.60-61-```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-```69-70-See [the Async Client documentation](async.md) for more details.modified:docs/quickstart.md+31 added-30 removed
1 # QuickStart2 3 !!! 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.5 6+ To run async examples directly you'll probably want to either use `ipython`,7+ or use Python 3.8 with `python -m asyncio`.8+9 First, start by importing HTTPX:10 11 ```python12 >>> import httpx1 unmodified line14 15 Now, let’s try to get a webpage.16 17 ```python17->>> r = httpx.get('https://httpbin.org/get')18+>>> r = await httpx.get('https://httpbin.org/get')19 >>> r20 <Response [200 OK]>21 ```22 23 Similarly, to make an HTTP POST request:24 25 ```python25->>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})26+>>> r = await httpx.post('https://httpbin.org/post', data={'key': 'value'})27 ```28 29 The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:30 31 ```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 ```37 38 ## Passing Parameters in URLs39 40 To include URL query parameters in the request, use the `params` keyword:41 42 ```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 ```46 47 To see how the values get encoding into the URL string, we can inspect the48 resulting URL that was used to make the request:6 unmodified lines55 You can also pass a list of items as a value:56 57 ```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.url61 URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')62 ```63 1 unmodified line65 66 HTTPX will automatically handle decoding the response content into Unicode text.67 68 ```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 lines110 111 Often Web API responses will be encoded as JSON.112 113 ```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 lines122 123 ```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 ```128 129 ## Sending Form Encoded Data130 2 unmodified lines133 which is used for HTML forms.134 135 ```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 lines149 Form encoded data can also include multiple values form a given key.150 151 ```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 lines169 You can also upload files, using HTTP multipart encoding:170 171 ```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 lines185 of items for the file value:186 187 ```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 lines203 For more complicated data structures you'll often want to use JSON encoding instead.204 205 ```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 lines233 234 We can inspect the HTTP status code of the response:235 236 ```python236->>> r = httpx.get('https://httpbin.org/get')237+>>> r = await httpx.get('https://httpbin.org/get')238 >>> r.status_code239 200240 ```241 6 unmodified lines248 249 We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):250 251 ```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_code254 404255 >>> not_found.raise_for_status()256 Traceback (most recent call last):44 unmodified lines301 302 Any cookies that are set on the response can be easily accessed:303 304 ```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 ```309 310 To include cookies in an outgoing request, use the `cookies` parameter:311 312 ```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 lines322 ```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 lines338 339 For example, GitHub redirects all HTTP requests to HTTPS.340 341 ```python341->>> r = httpx.get('http://github.com/')342+>>> r = await httpx.get('http://github.com/')343 >>> r.url344 URL('https://github.com/')345 >>> r.status_code346 2003 unmodified lines350 351 You can modify the default redirection handling with the allow_redirects parameter:352 353 ```python353->>> r = httpx.get('http://github.com/', allow_redirects=False)354+>>> r = await httpx.get('http://github.com/', allow_redirects=False)355 >>> r.status_code356 301357 >>> r.history358 []1 unmodified line360 361 If you’re making a `HEAD` request, you can use this to enable redirection:362 363 ```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 lines377 The default timeout for network inactivity is five seconds. You can modify the378 value to be more or less strict:379 380 ```python380->>> httpx.get('https://github.com/', timeout=0.001)381+>>> await httpx.get('https://github.com/', timeout=0.001)382 ```383 384 For advanced timeout management, see [Timeout fine-tuning](https://www.encode.io/httpx/advanced/#timeout-fine-tuning).385 5 unmodified lines391 plaintext `str` or `bytes` objects as the `auth` argument to the request392 functions:393 394 ```python394->>> httpx.get("https://example.com", auth=("my_user", "password123"))395+>>> await httpx.get("https://example.com", auth=("my_user", "password123"))396 ```397 398 To provide credentials for Digest authentication you'll need to instantiate399 a `DigestAuth` object with the plaintext username and password as arguments.1 unmodified line401 as above:402 403 ```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 line2 Dispatch classes handle the raw network connections and the implementation3 details of making the HTTP request and receiving the response.4 """5 from .asgi import ASGIDispatch6-from .wsgi import WSGIDispatch6 8-__all__ = ["ASGIDispatch", "WSGIDispatch"]7+__all__ = ["ASGIDispatch"]modified:httpx/dispatch/asgi.py+6 added-6 removed
1 unmodified line2 3 from ..concurrency.asyncio import AsyncioBackend4 from ..concurrency.base import ConcurrencyBackend5 from ..config import CertTypes, TimeoutTypes, VerifyTypes6-from ..models import AsyncRequest, AsyncResponse6+from ..models import Request, Response7 from ..utils import MessageLoggerASGIMiddleware, get_logger8-from .base import AsyncDispatcher8+from .base import Dispatcher9 10 logger = get_logger(__name__)11 12 13-class ASGIDispatch(AsyncDispatcher):13+class ASGIDispatch(Dispatcher):14 """15 A custom dispatcher that handles sending requests directly to an ASGI app.16 17 The simplest way to use this functionality is to use the `app` argument.43 unmodified lines61 self.backend = AsyncioBackend() if backend is None else backend62 63 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:70 71 scope = {72 "type": "http",73 "asgi": {"version": "3.0"},71 unmodified lines145 await background.close(app_exc)146 if app_exc is not None and self.raise_app_exceptions:147 raise app_exc148 149- 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 linesmodified:httpx/dispatch/base.py+8 added-59 removed
1 unmodified line2 from types import TracebackType3 4 from ..config import CertTypes, TimeoutTypes, VerifyTypes5 from ..models import (6- AsyncRequest,7- AsyncRequestData,8- AsyncResponse,6 HeaderTypes,7 QueryParamTypes,8 Request,9 RequestData,1 unmodified line11 URLTypes,12 )13 14 18-class AsyncDispatcher:15+class 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.18 19 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 lines25 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)41-42- 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: nocover50-51- async def close(self) -> None:52- pass # pragma: nocover53-54- async def __aenter__(self) -> "AsyncDispatcher":55- return self56-57- 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()64-65-66-class Dispatcher:67- """68- Base class for synchronous dispatcher classes, that handle sending the request.69-70- 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- """74-75- 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)38 90- 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: nocover47 99- def close(self) -> None:48+ async def close(self) -> None:49 pass # pragma: nocover50 102- def __enter__(self) -> "Dispatcher":51+ async def __aenter__(self) -> "Dispatcher":52 return self53 105- 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 lines10 PoolLimits,11 TimeoutTypes,12 VerifyTypes,13 )14-from ..models import AsyncRequest, AsyncResponse, Origin14+from ..models import Origin, Request, Response15 from ..utils import get_logger16-from .base import AsyncDispatcher16+from .base import Dispatcher17 from .connection import HTTPConnection18 19 CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]20 56 unmodified lines77 def __len__(self) -> int:78 return len(self.all)79 80 81-class ConnectionPool(AsyncDispatcher):81+class ConnectionPool(Dispatcher):82 def __init__(83 self,84 *,85 verify: VerifyTypes = True,25 unmodified lines111 return len(self.keepalive_connections) + len(self.active_connections)112 113 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=timeout66 unmodified linesmodified:httpx/dispatch/connection.py+5 added-5 removed
12 unmodified lines13 TimeoutConfig,14 TimeoutTypes,15 VerifyTypes,16 )17-from ..models import AsyncRequest, AsyncResponse, Origin17+from ..models import Origin, Request, Response18 from ..utils import get_logger19-from .base import AsyncDispatcher19+from .base import Dispatcher20 from .http2 import HTTP2Connection21 from .http11 import HTTP11Connection22 23 # Callback signature: async def callback(conn: HTTPConnection) -> None2 unmodified lines26 27 logger = get_logger(__name__)28 29 30-class HTTPConnection(AsyncDispatcher):30+class HTTPConnection(Dispatcher):31 def __init__(32 self,33 origin: typing.Union[str, Origin],34 verify: VerifyTypes = True,16 unmodified lines51 self.h2_connection = None # type: typing.Optional[HTTP2Connection]52 53 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)62 63 if self.h2_connection is not None:91 unmodified linesmodified:httpx/dispatch/http11.py+4 added-6 removed
3 unmodified lines4 5 from ..concurrency.base import BaseSocketStream, ConcurrencyBackend, TimeoutFlag6 from ..config import TimeoutConfig, TimeoutTypes7 from ..exceptions import ConnectionClosed, ProtocolError8-from ..models import AsyncRequest, AsyncResponse8+from ..models import Request, Response9 from ..utils import get_logger10 11 H11Event = typing.Union[12 h11.Request,28 unmodified lines41 self.on_release = on_release42 self.h11_state = h11.Connection(our_role=h11.CLIENT)43 self.timeout_flag = TimeoutFlag()44 45- 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)47 48 await self._send_request(request, timeout)49 1 unmodified line51 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)54 57- return AsyncResponse(55+ return Response(56 status_code=status_code,57 http_version=http_version,58 headers=headers,59 content=content,11 unmodified lines71 pass72 await self.stream.close()73 74 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 linesmodified:httpx/dispatch/http2.py+4 added-6 removed
11 unmodified lines12 TimeoutFlag,13 )14 from ..config import TimeoutConfig, TimeoutTypes15 from ..exceptions import ProtocolError16-from ..models import AsyncRequest, AsyncResponse16+from ..models import Request, Response17 from ..utils import get_logger18 19 logger = get_logger(__name__)20 15 unmodified lines36 self.timeout_flags = {} # type: typing.Dict[int, TimeoutFlag]37 self.initialized = False38 self.window_update_received = {} # type: typing.Dict[int, BaseEvent]39 40- 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)42 43 # Start sending the request.44 if not self.initialized:10 unmodified lines55 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)58 61- return AsyncResponse(59+ return Response(60 status_code=status_code,61 http_version="HTTP/2",62 headers=headers,63 content=content,32 unmodified lines96 self.stream.write_no_block(data_to_send)97 self.initialized = True98 99 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 linesmodified:httpx/dispatch/proxy_http.py+4 added-12 removed
13 unmodified lines14 VerifyTypes,15 )16 from ..exceptions import ProxyError17 from ..middleware.basic_auth import build_basic_auth_header18-from ..models import (19- URL,20- AsyncRequest,21- AsyncResponse,22- Headers,23- HeaderTypes,24- Origin,25- URLTypes,26-)18+from ..models import URL, Headers, HeaderTypes, Origin, Request, Response, URLTypes19 from ..utils import get_logger20 from .connection import HTTPConnection21 from .connection_pool import ConnectionPool22 from .http2 import HTTP2Connection90 unmodified lines113 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 lines216 ) or self.proxy_mode == HTTPProxyMode.FORWARD_ONLY217 218 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:225 226 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 URL17 unmodified linesdeleted:httpx/dispatch/threaded.py-97 removed
1-from ..concurrency.base import ConcurrencyBackend2-from ..config import CertTypes, TimeoutTypes, VerifyTypes3-from ..models import (4- AsyncRequest,5- AsyncRequestData,6- AsyncResponse,7- AsyncResponseContent,8- Request,9- RequestData,10- Response,11- ResponseContent,12-)13-from .base import AsyncDispatcher, Dispatcher14-15-16-class 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- """22-23- def __init__(self, dispatch: Dispatcher, backend: ConcurrencyBackend) -> None:24- self.sync_dispatcher = dispatch25- self.backend = backend26-27- 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.backend35-36- data = getattr(request, "content", getattr(request, "content_aiter", None))37- sync_data = self._sync_request_data(data)38-39- sync_request = Request(40- method=request.method,41- url=request.url,42- headers=request.headers,43- data=sync_data,44- )45-46- 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)55-56- content = getattr(57- sync_response, "_raw_content", getattr(sync_response, "_raw_stream", None)58- )59-60- async_content = self._async_response_content(content)61-62- async def async_on_close() -> None:63- nonlocal concurrency_backend, sync_response64- await concurrency_backend.run_in_threadpool(sync_response.close)65-66- 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- )75-76- 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)83-84- def _async_response_content(self, content: ResponseContent) -> AsyncResponseContent:85- if isinstance(content, bytes):86- return content87-88- # 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)92-93- def _sync_request_data(self, data: AsyncRequestData) -> RequestData:94- if isinstance(data, bytes):95- return data96-97- return self.backend.iterate(data)deleted:httpx/dispatch/wsgi.py-164 removed
1-import io2-import typing3-4-from ..config import CertTypes, TimeoutTypes, VerifyTypes5-from ..models import Request, Response6-from .base import Dispatcher7-8-9-class WSGIDispatch(Dispatcher):10- """11- A custom dispatcher that handles sending requests directly to an ASGI app.12-13- 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:16-17- ```18- client = httpx.Client(app=app)19- ```20-21- Alternatively, you can setup the dispatch instance explicitly.22- This allows you to include any additional configuration arguments specific23- to the WSGIDispatch class:24-25- ```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)32-33-34- Arguments:35-36- * `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- """44-45- 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_addr56-57- 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] = value85-86- seen_status = None87- seen_response_headers = None88- seen_exc_info = None89-90- 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_info97-98- result = self.app(environ, start_response)99-100- 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]104-105- 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- )112-113-114-class BodyStream(io.RawIOBase):115- def __init__(self, iterator: typing.Iterator[bytes]) -> None:116- self._iterator = iterator117- self._buffer = b""118- self._closed = False119-120- def read(self, size: int = -1) -> bytes:121- if self._closed:122- return b""123-124- if size == -1:125- return self.readall()126-127- try:128- while len(self._buffer) < size:129- self._buffer += next(self._iterator)130- except StopIteration:131- self._closed = True132- return self._buffer133-134- output = self._buffer[:size]135- self._buffer = self._buffer[size:]136- return output137-138- def readall(self) -> bytes:139- if self._closed:140- raise OSError("Stream closed") # pragma: nocover141-142- for chunk in self._iterator:143- self._buffer += chunk144-145- self._closed = True146- return self._buffer147-148- def readinto(self, b: bytearray) -> typing.Optional[int]: # pragma: nocover149- output = self.read(len(b))150- count = len(output)151- b[:count] = output152- return count153-154- def write(self, b: bytes) -> int:155- raise OSError("Operation not supported") # pragma: nocover156-157- def fileno(self) -> int:158- raise OSError("Operation not supported") # pragma: nocover159-160- def seek(self, offset: int, whence: int = 0) -> int:161- raise OSError("Operation not supported") # pragma: nocover162-163- def truncate(self, size: int = None) -> int:164- raise OSError("Operation not supported") # pragma: nocovermodified:httpx/middleware/base.py+3 added-3 removed
1 import typing2 3-from ..models import AsyncRequest, AsyncResponse3+from ..models import Request, Response4 5 6 class 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 covermodified:httpx/middleware/basic_auth.py+3 added-3 removed
1 import typing2 from base64 import b64encode3 4-from ..models import AsyncRequest, AsyncResponse4+from ..models import Request, Response5 from ..utils import to_bytes6 from .base import BaseMiddleware7 8 3 unmodified lines12 ):13 self.authorization_header = build_basic_auth_header(username, password)14 15 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)20 21 6 unmodified linesmodified:httpx/middleware/custom_auth.py+4 added-4 removed
1 import typing2 3-from ..models import AsyncRequest, AsyncResponse3+from ..models import Request, Response4 from .base import BaseMiddleware5 6 7 class CustomAuthMiddleware(BaseMiddleware):8- def __init__(self, auth: typing.Callable[[AsyncRequest], AsyncRequest]):8+ def __init__(self, auth: typing.Callable[[Request], Request]):9 self.auth = auth10 11 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 lines5 import typing6 from urllib.request import parse_http_list7 8 from ..exceptions import ProtocolError9-from ..models import AsyncRequest, AsyncResponse, StatusCode9+from ..models import Request, Response, StatusCode10 from ..utils import to_bytes, to_str, unquote11 from .base import BaseMiddleware12 13 15 unmodified lines29 self.username = to_bytes(username)30 self.password = to_bytes(password)31 32 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.headers9 unmodified lines48 request.headers["Authorization"] = self._build_auth_header(request, challenge)49 return await get_response(request)50 51 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]55 56 def digest(data: bytes) -> bytes:125 unmodified linesmodified:httpx/middleware/redirect.py+10 added-12 removed
1 unmodified line2 import typing3 4 from ..config import DEFAULT_MAX_REDIRECTS5 from ..exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects6-from ..models import URL, AsyncRequest, AsyncResponse, Cookies, Headers6+from ..models import URL, Cookies, Headers, Request, Response7 from ..status_codes import codes8 from .base import BaseMiddleware9 10 6 unmodified lines17 ):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] = []22 23 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 lines42 43 response.call_next = functools.partial(self, next_request, get_response)44 return response45 46- 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 )55 58- 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 lines75 method = "GET"76 77 return method78 81- 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 lines94 url = url.copy_with(fragment=request.url.fragment)95 96 return url97 100- 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 lines118 headers.pop("Cookie", None)119 120 return headers121 124- 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 linesmodified:httpx/__init__.py+2 added-12 removed
1 from .__version__ import __description__, __title__, __version__2 from .api import delete, get, head, options, patch, post, put, request3-from .client import AsyncClient, Client3+from .client import Client4 from .concurrency.asyncio import AsyncioBackend5 from .concurrency.base import (6 BaseBackgroundManager,7 BasePoolSemaphore,10 unmodified lines18 TimeoutConfig,19 TimeoutTypes,20 VerifyTypes,21 )22-from .dispatch.base import AsyncDispatcher, Dispatcher22+from .dispatch.base import Dispatcher23 from .dispatch.connection import HTTPConnection24 from .dispatch.connection_pool import ConnectionPool25 from .dispatch.proxy_http import HTTPProxy, HTTPProxyMode26 from .exceptions import (18 unmodified lines45 )46 from .middleware.digest_auth import DigestAuth47 from .models import (48 URL,49- AsyncRequest,50- AsyncRequestData,51- AsyncResponse,52- AsyncResponseContent,49 AuthTypes,50 Cookies,51 CookieTypes,52 Headers,22 unmodified lines75 "post",76 "patch",77 "put",78 "request",83- "AsyncClient",79 "Client",80 "AsyncioBackend",81 "USER_AGENT",82 "CertTypes",24 unmodified lines107 "ProxyError",108 "Timeout",109 "TooManyRedirects",110 "WriteTimeout",116- "AsyncDispatcher",111 "BaseSocketStream",112 "ConcurrencyBackend",113 "Dispatcher",114 "URL",2 unmodified lines117 "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 linesmodified:httpx/api.py+42 added-40 removed
1 import typing2 3 from .client import Client4-from .config import CertTypes, TimeoutTypes, VerifyTypes4+from .config import DEFAULT_TIMEOUT_CONFIG, CertTypes, TimeoutTypes, VerifyTypes5 from .models import (6 AuthTypes,7 CookieTypes,8 HeaderTypes,4 unmodified lines13 URLTypes,14 )15 16 17-def request(17+async def request(18 method: str,19 url: URLTypes,20 *,21 params: QueryParamTypes = None,2 unmodified lines24 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 lines74 Usage:75 76 ```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 lines98 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 )103 104 103-def get(105+async def get(106 url: URLTypes,107 *,108 params: QueryParamTypes = None,109 headers: HeaderTypes = None,2 unmodified lines112 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 line123 124 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 lines139 trust_env=trust_env,140 )141 142 141-def options(143+async def options(144 url: URLTypes,145 *,146 params: QueryParamTypes = None,147 headers: HeaderTypes = None,2 unmodified lines150 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 line161 162 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 lines177 trust_env=trust_env,178 )179 180 179-def head(181+async 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 lines201 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 lines217 trust_env=trust_env,218 )219 220 219-def post(221+async def post(222 url: URLTypes,223 *,224 data: RequestData = None,225 files: RequestFiles = None,5 unmodified lines231 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.240 241 **Parameters**: See `httpx.request`.242 """241- return request(243+ return await request(244 "POST",245 url,246 data=data,247 files=files,10 unmodified lines258 trust_env=trust_env,259 )260 261 260-def put(262+async def put(263 url: URLTypes,264 *,265 data: RequestData = None,266 files: RequestFiles = None,5 unmodified lines272 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.281 282 **Parameters**: See `httpx.request`.283 """282- return request(284+ return await request(285 "PUT",286 url,287 data=data,288 files=files,10 unmodified lines299 trust_env=trust_env,300 )301 302 301-def patch(303+async def patch(304 url: URLTypes,305 *,306 data: RequestData = None,307 files: RequestFiles = None,5 unmodified lines313 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.322 323 **Parameters**: See `httpx.request`.324 """323- return request(325+ return await request(326 "PATCH",327 url,328 data=data,329 files=files,10 unmodified lines340 trust_env=trust_env,341 )342 343 342-def delete(344+async def delete(345 url: URLTypes,346 *,347 params: QueryParamTypes = None,348 headers: HeaderTypes = None,2 unmodified lines351 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 line362 363 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 linesmodified:httpx/client.py+88 added-591 removed
1 import functools2-import inspect2 import netrc3 import typing4 from types import TracebackType5 11 unmodified lines17 TimeoutTypes,18 VerifyTypes,19 )20 from .dispatch.asgi import ASGIDispatch22-from .dispatch.base import AsyncDispatcher, Dispatcher21+from .dispatch.base import Dispatcher22 from .dispatch.connection_pool import ConnectionPool23 from .dispatch.proxy_http import HTTPProxy25-from .dispatch.threaded import ThreadedDispatcher26-from .dispatch.wsgi import WSGIDispatch24 from .exceptions import HTTPError, InvalidURL25 from .middleware.base import BaseMiddleware26 from .middleware.basic_auth import BasicAuthMiddleware27 from .middleware.custom_auth import CustomAuthMiddleware28 from .middleware.redirect import RedirectMiddleware29 from .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 )45 from .utils import ElapsedTimer, get_environment_proxies, get_logger, get_netrc46 47 logger = get_logger(__name__)48 49 57-class BaseClient:50+class Client:51+ """52+ An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.53+54+ Usage:55+56+ ```57+ >>> client = httpx.Client()58+ >>> response = client.get('https://example.org')59+ ```60+61+ **Parameters:**62+63+ * **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+ """100+101 def __init__(102 self,103 *,104 auth: AuthTypes = None,7 unmodified lines112 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()124 82- self.check_concurrency_backend(backend)83-125 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)127 128 self.trust_env = True if trust_env is None else trust_env129 130 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 line137 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 = dispatch141 142 if base_url is None:143 self.base_url = URL("", allow_relative=True)144 else:6 unmodified lines151 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 = backend157 158 if proxies is None and trust_env:159 proxies = typing.cast(ProxiesTypes, get_environment_proxies())160 129- 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 lines201 @params.setter202 def params(self, params: QueryParamTypes) -> None:203 self._params = QueryParams(params)204 173- def check_concurrency_backend(self, backend: ConcurrencyBackend) -> None:174- pass # pragma: no cover175-205 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 lines236 return params237 238 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".')252 253 dispatch = self._dispatcher_for_request(request, self.proxies)254 226- 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 lines304 305 return await get_response(request)306 307 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 lines316 317 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 )323 324 if request.url.username or request.url.password:16 unmodified lines341 def _get_netrc(self) -> typing.Optional[netrc.netrc]:342 return get_netrc()343 344 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 == 44318 unmodified lines370 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 lines395 headers=headers,396 cookies=cookies,397 )398 369-370-class AsyncClient(BaseClient):399 async def get(400 self,401 url: URLTypes,402 *,6 unmodified lines409 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 lines439 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 lines469 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 lines489 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 lines502 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 lines525 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 lines538 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 lines561 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 lines574 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 lines607 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 lines628 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 lines641 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 lines666 return response667 668 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 lines690 691 async def close(self) -> None:692 await self.dispatch.close()693 666- async def __aenter__(self) -> "AsyncClient":694+ async def __aenter__(self) -> "Client":695 return self696 697 async def __aexit__(698 self,3 unmodified lines702 ) -> None:703 await self.close()704 705 678-class Client(BaseClient):679- """680- An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc.681-682- Usage:683-684- ```685- >>> client = httpx.Client()686- >>> response = client.get('https://example.org')687- ```688-689- **Parameters:**690-691- * **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- """728-729- 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.737-738- if isinstance(backend, AsyncioBackend):739- return740-741- if hasattr(backend, "loop"):742- # Most likely a proxy class.743- return744-745- raise ValueError("'Client' only supports asyncio-based concurrency backends")746-747- 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 data756-757- # 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)761-762- def _sync_data(self, data: AsyncResponseContent) -> ResponseContent:763- if isinstance(data, bytes):764- return data765-766- # 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)770-771- 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.792-793- **Parameters:**794-795- * **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.825-826- **Returns:** `Response`827-828- Usage:829-830- ```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- )858-859- 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_backend875-876- 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)888-889- content = getattr(890- async_response, "_raw_content", getattr(async_response, "_raw_stream", None)891- )892-893- sync_content = self._sync_data(content)894-895- def sync_on_close() -> None:896- nonlocal concurrency_backend, async_response897- concurrency_backend.run(async_response.on_close)898-899- 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 response915-916- 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.933-934- **Parameters**: See `Client.request`.935-936- 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- )953-954- 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.971-972- **Parameters**: See `Client.request`.973-974- 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- )991-992- 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.1009-1010- **Parameters**: See `Client.request`.1011-1012- 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- )1031-1032- 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.1052-1053- **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- )1072-1073- 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.1093-1094- **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- )1113-1114- 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.1134-1135- **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- )1154-1155- 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.1172-1173- **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- )1189-1190- 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)1196-1197- def __enter__(self) -> "Client":1198- return self1199-1200- 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()1207-1208-706 def _proxies_to_dispatchers(707 proxies: typing.Optional[ProxiesTypes],708 verify: VerifyTypes,709 cert: typing.Optional[CertTypes],1 unmodified line711 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 lines732 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 linesmodified:httpx/exceptions.py+2 added-5 removed
1 import typing2 3 if typing.TYPE_CHECKING:4- from .models import BaseRequest, BaseResponse # pragma: nocover4+ from .models import Request, Response # pragma: nocover5 6 7 class HTTPError(Exception):8 """9 Base class for Httpx exception10 """11 12 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 linesmodified:httpx/models.py+44 added-226 removed
42 unmodified lines43 )44 45 if 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: F40148 49 PrimitiveData = typing.Optional[typing.Union[str, int, float, bool]]50 51 URLTypes = typing.Union["URL", str]14 unmodified lines66 CookieTypes = typing.Union["Cookies", CookieJar, typing.Dict[str, str]]67 68 AuthTypes = 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 ]73 74 ProxiesTypes = 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 ]77 80-AsyncRequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]78+RequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]79 82-RequestData = typing.Union[dict, str, bytes, typing.Iterator[bytes]]83-80 RequestFiles = typing.Dict[81 str,82 typing.Union[83 typing.IO[typing.AnyStr], # file3 unmodified lines87 ], # (filename, file, content_type)88 ],89 ]90 95-AsyncResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]91+ResponseContent = typing.Union[bytes, typing.AsyncIterator[bytes]]92 97-ResponseContent = typing.Union[bytes, typing.Iterator[bytes]]93 99-94 class URL:95 def __init__(96 self,97 url: URLTypes,487 unmodified lines585 return f"{class_name}({as_dict!r}{encoding_str})"586 return f"{class_name}({as_list!r}{encoding_str})"587 588 595-class BaseRequest:589+class 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()623 624 def encode_data(625 self, data: dict = None, files: RequestFiles = None, json: typing.Any = None626 ) -> typing.Tuple[bytes, str]:58 unmodified lines685 class_name = self.__class__.__name__686 url = str(self.url)687 return f"<{class_name}({self.method!r}, {url!r})>"688 677-678-class 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- )694-695- 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()710-689 async def read(self) -> bytes:690 """691 Read and return the response content.692 """8 unmodified lines701 elif self.content:702 yield self.content703 704 727-class Request(BaseRequest):705+class 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- )743-744- 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 = data758-759- self.prepare()760-761- def read(self) -> bytes:762- if not hasattr(self, "content"):763- self.content = b"".join([part for part in self.stream()])764- return self.content765-766- 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.content772-773-774-class 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_version3 unmodified lines723 self.on_close = on_close724 self.elapsed = datetime.timedelta(0) if elapsed is None else elapsed725 self.call_next: typing.Optional[typing.Callable] = None726 727+ self.history = [] if history is None else list(history)728+729+ 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 = content737+738 @property739 def reason_phrase(self) -> str:740 return StatusCode.get_reason_phrase(self.status_code)741 155 unmodified lines897 898 def __repr__(self) -> str:899 return f"<Response [{self.status_code} {self.reason_phrase}]>"900 957-958-class 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- )979-980- self.history = [] if history is None else list(history)981-982- 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 = content990-901 async def read(self) -> bytes:902 """903 Read and return the response content.904 """40 unmodified lines945 async for part in self._raw_stream:946 yield part947 await self.close()948 1039- 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 lines965 if self.on_close is not None:966 await self.on_close()967 968 1059-class 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- )1080-1081- self.history = [] if history is None else list(history)1082-1083- 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 = content1091-1092- 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._content1099-1100- 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()1111-1112- 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()1122-1123- 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()1134-1135- self.is_stream_consumed = True1136- for part in self._raw_stream:1137- yield part1138- self.close()1139-1140- 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()1149-1150-969 class Cookies(MutableMapping):970 """971 HTTP Cookies, as a mutable mapping.972 """10 unmodified lines983 self.jar.set_cookie(cookie)984 else:985 self.jar = cookies986 1169- 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 None1 unmodified line993 urllib_request = self._CookieCompatRequest(response.request)994 995 self.jar.extract_cookies(urlib_response, urllib_request) # type: ignore996 1179- 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 lines1112 Wraps a `Request` instance up in a compatibility interface suitable1113 for use with `CookieJar` operations.1114 """1115 1298- 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 lines1130 Wraps a `Request` instance up in a compatibility interface suitable1131 for use with `CookieJar` operations.1132 """1133 1316- def __init__(self, response: BaseResponse):1134+ def __init__(self, response: Response):1135 self.response = response1136 1137 def info(self) -> email.message.Message:1138 info = email.message.Message()3 unmodified linesmodified:tests/client/test_async_client.py+16 added-16 removed
5 unmodified lines6 7 8 async 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 lines19 20 async 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 lines36 """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 lines47 48 49 async 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 == 20054 55 56 async 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 == 20061 62 63 async 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!"70 71 72 async 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.content3 unmodified lines81 async def hello_world():82 yield b"Hello, "83 yield b"world!"84 85- 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 == 20088 89 90 async 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 lines102 assert response.raise_for_status() is None103 104 105 async 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!"110 111 112 async 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 == ""117 118 119 async 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 == 200123 124 125 async 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 == 200129 130 131 async 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 line138 async def test_100_continue(server, backend):139 headers = {"Expect": "100-continue"}140 data = b"Echo request body"141 142- 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 lines151 async 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 lines5 import pytest6 7 from 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 )19 20 21-class MockDispatch(AsyncDispatcher):21+class MockDispatch(Dispatcher):22 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:23 self.auth_header = auth_header24 self.status_code = status_code25 26 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 )38 39 40-class MockDigestAuthDispatch(AsyncDispatcher):40+class MockDigestAuthDispatch(Dispatcher):41 def __init__(42 self,43 algorithm: str = "SHA-256",44 send_response_after_attempt: int = 1,7 unmodified lines52 self._response_count = 053 54 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)63 64 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)66 67- 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_nonce16 unmodified lines88 89 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)93 94 95+@pytest.mark.asyncio95-def test_basic_auth():96+async def test_basic_auth():97 url = "https://example.org/"98 auth = ("tomchristie", "password123")99 99- 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)102 103 assert response.status_code == 200104 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}105 106 107+@pytest.mark.asyncio106-def test_basic_auth_in_url():108+async def test_basic_auth_in_url():109 url = "https://tomchristie:password123@example.org/"110 109- with Client(dispatch=MockDispatch()) as client:110- response = client.get(url)111+ client = Client(dispatch=MockDispatch())112+ response = await client.get(url)113 114 assert response.status_code == 200115 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}116 117 118+@pytest.mark.asyncio116-def test_basic_auth_on_session():119+async def test_basic_auth_on_session():120 url = "https://example.org/"121 auth = ("tomchristie", "password123")122 120- 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)125 126 assert response.status_code == 200127 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}128 129 130+@pytest.mark.asyncio127-def test_custom_auth():131+async def test_custom_auth():132 url = "https://example.org/"133 134 def auth(request):135 request.headers["Authorization"] = "Token 123"136 return request137 134- 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)140 141 assert response.status_code == 200142 assert response.json() == {"auth": "Token 123"}143 144 145+@pytest.mark.asyncio141-def test_netrc_auth():146+async def test_netrc_auth():147 os.environ["NETRC"] = "tests/.netrc"148 url = "http://netrcexample.org"149 145- with Client(dispatch=MockDispatch()) as client:146- response = client.get(url)150+ client = Client(dispatch=MockDispatch())151+ response = await client.get(url)152 153 assert response.status_code == 200154 assert response.json() == {155 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"156 }157 158 159+@pytest.mark.asyncio154-def test_trust_env_auth():160+async def test_trust_env_auth():161 os.environ["NETRC"] = "tests/.netrc"162 url = "http://netrcexample.org"163 158- 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)166 167 assert response.status_code == 200168 assert response.json() == {"auth": None}169 164- 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)172 173 assert response.status_code == 200174 assert response.json() == {175 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"6 unmodified lines182 assert url == URL(url)183 assert expected == repr(URL(url))184 185 186+@pytest.mark.asyncio180-def test_auth_hidden_header():187+async def test_auth_hidden_header():188 url = "https://example.org/"189 auth = ("example-username", "example-password")190 184- 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)193 194 assert "'authorization': '[secure]'" in str(response.request.headers)195 196 197+@pytest.mark.asyncio190-def test_auth_invalid_type():198+async 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)203 204 205+@pytest.mark.asyncio197-def test_digest_auth_returns_no_auth_if_no_digest_header_in_response():206+async 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")209 201- 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)212 213 assert response.status_code == 200214 assert response.json() == {"auth": None}215 216 208-def test_digest_auth_200_response_including_digest_auth_header_is_returned_as_is():217+@pytest.mark.asyncio218+async 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"'222 213- 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)225 226 assert response.status_code == 200227 assert response.json() == {"auth": None}228 229 222-def test_digest_auth_401_response_without_digest_auth_header_is_returned_as_is():230+@pytest.mark.asyncio231+async def test_digest_auth_401_response_without_digest_auth_header():232 url = "https://example.org/"233 auth = DigestAuth(username="tomchristie", password="password123")234 226- 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)237 238 assert response.status_code == 401239 assert response.json() == {"auth": None}240 10 unmodified lines251 ("SHA-512", 64, 128),252 ("SHA-512-SESS", 64, 128),253 ],254 )255+@pytest.mark.asyncio246-def test_digest_auth(algorithm, expected_hash_length, expected_response_length):256+async def test_digest_auth(algorithm, expected_hash_length, expected_response_length):257 url = "https://example.org/"258 auth = DigestAuth(username="tomchristie", password="password123")259 250- 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)262 263 assert response.status_code == 200264 auth = response.json()["auth"]265 assert auth.startswith("Digest ")12 unmodified lines278 assert digest_data["nc"] == "00000001"279 assert len(digest_data["cnonce"]) == 16 + 2280 281 282+@pytest.mark.asyncio272-def test_digest_auth_no_specified_qop():283+async def test_digest_auth_no_specified_qop():284 url = "https://example.org/"285 auth = DigestAuth(username="tomchristie", password="password123")286 276- 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)289 290 assert response.status_code == 200291 auth = response.json()["auth"]292 assert auth.startswith("Digest ")13 unmodified lines306 assert digest_data["algorithm"] == "SHA-256"307 308 309 @pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))310+@pytest.mark.asyncio299-def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str):311+async 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")314 303- 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)317 318 319+@pytest.mark.asyncio307-def test_digest_auth_qop_auth_int_not_implemented():320+async 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"))324 325 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)327 328 329+@pytest.mark.asyncio316-def test_digest_auth_qop_must_be_auth_or_auth_int():330+async 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"))334 335 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)337 338 339+@pytest.mark.asyncio325-def test_digest_auth_incorrect_credentials():340+async def test_digest_auth_incorrect_credentials():341 url = "https://example.org/"342 auth = DigestAuth(username="tomchristie", password="password123")343 329- 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)346 347 assert response.status_code == 401348 349 6 unmodified lines356 'qop="auth,auth-int",nonce="abc",opaque="xyz"',357 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list358 ],359 )360+@pytest.mark.asyncio347-def test_digest_auth_raises_protocol_error_on_malformed_header(auth_header: str):361+async 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))365 366 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 lines5 6 import httpx7 8 9+@pytest.mark.asyncio9-def test_get(server):10+async 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 lines23 assert repr(response) == "<Response [200 OK]>"24 assert response.elapsed > timedelta(0)25 26 27+@pytest.mark.asyncio26-def test_build_request(server):28+async def test_build_request(server):29 url = server.url.copy_with(path="/echo_headers")30 headers = {"Custom-header": "value"}31 30- 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)36 37 assert response.status_code == 20038 assert response.url == url39 40 assert response.json()["Custom-header"] == "value"41 42 43+@pytest.mark.asyncio41-def test_post(server):42- with httpx.Client() as http:43- response = http.post(server.url, data=b"Hello, world!")44+async 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"49 50 51+@pytest.mark.asyncio48-def test_post_json(server):49- with httpx.Client() as http:50- response = http.post(server.url, json={"text": "Hello, world!"})52+async 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"57 58 59+@pytest.mark.asyncio55-def test_stream_response(server):56- with httpx.Client() as http:57- response = http.get(server.url, stream=True)60+async 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!"66 67 68+@pytest.mark.asyncio63-def test_stream_iterator(server):64- with httpx.Client() as http:65- response = http.get(server.url, stream=True)69+async 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!"77 78 79+@pytest.mark.asyncio73-def test_raw_iterator(server):74- with httpx.Client() as http:75- response = http.get(server.url, stream=True)80+async 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()89 90 91+@pytest.mark.asyncio84-def test_raise_for_status(server):85- with httpx.Client() as client:92+async 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 lines102 else:103 assert response.raise_for_status() is None104 105 106+@pytest.mark.asyncio98-def test_options(server):99- with httpx.Client() as http:100- response = http.options(server.url)107+async 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"112 113 114+@pytest.mark.asyncio105-def test_head(server):106- with httpx.Client() as http:107- response = http.head(server.url)115+async 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"120 121 122+@pytest.mark.asyncio112-def test_put(server):113- with httpx.Client() as http:114- response = http.put(server.url, data=b"Hello, world!")123+async 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"128 129 130+@pytest.mark.asyncio119-def test_patch(server):120- with httpx.Client() as http:121- response = http.patch(server.url, data=b"Hello, world!")131+async 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"136 137 138+@pytest.mark.asyncio126-def test_delete(server):127- with httpx.Client() as http:128- response = http.delete(server.url)139+async 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"144 145 146+@pytest.mark.asyncio133-def test_base_url(server):147+async 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_url153 154 155+@pytest.mark.asyncio141-def test_uds(uds_server):156+async 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 lines171 assert url.scheme == "https"172 assert url.is_ssl173 174 160-class DerivedFromAsyncioBackend(httpx.AsyncioBackend):161- pass162-163-164-class AnyBackend:165- pass166-167-168-def test_client_backend_must_be_asyncio_based():169- httpx.Client(backend=httpx.AsyncioBackend())170- httpx.Client(backend=DerivedFromAsyncioBackend())171-172- with pytest.raises(ValueError):173- httpx.Client(backend=AnyBackend())174-175-176-def 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.asyncio176+async 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)180 181 182-def test_elapsed_delay_ignores_read_time(server):183- with httpx.Client() as http:184- response = http.get(182+@pytest.mark.asyncio183+async 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
1 import json2 from http.cookiejar import Cookie, CookieJar3 4+import pytest5+6 from 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 )16 17 16-class MockDispatch(AsyncDispatcher):18+class 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)32 33 34+@pytest.mark.asyncio32-def test_set_cookie():35+async 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"}41 39- 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)44 45 assert response.status_code == 20046 assert response.json() == {"cookies": "example-name=example-value"}47 48 49+@pytest.mark.asyncio46-def test_set_cookie_with_cookiejar():50+async def test_set_cookie_with_cookiejar():51 """52 Send a request including a cookie, using a `CookieJar` instance.53 """54 19 unmodified lines74 rfc2109=False,75 )76 cookies.set_cookie(cookie)77 74- 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)80 81 assert response.status_code == 20082 assert response.json() == {"cookies": "example-name=example-value"}83 84 85+@pytest.mark.asyncio81-def test_setting_client_cookies_to_cookiejar():86+async def test_setting_client_cookies_to_cookiejar():87 """88 Send a request including a cookie, using a `CookieJar` instance.89 """90 19 unmodified lines110 rfc2109=False,111 )112 cookies.set_cookie(cookie)113 109- 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)117 118 assert response.status_code == 200119 assert response.json() == {"cookies": "example-name=example-value"}120 121 122+@pytest.mark.asyncio117-def test_set_cookie_with_cookies_model():123+async def test_set_cookie_with_cookies_model():124 """125 Send a request including a cookie, using a `Cookies` instance.126 """127 128 url = "http://example.org/echo_cookies"129 cookies = Cookies()130 cookies["example-name"] = "example-value"131 126- 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)134 135 assert response.status_code == 200136 assert response.json() == {"cookies": "example-name=example-value"}137 138 139+@pytest.mark.asyncio133-def test_get_cookie():140+async def test_get_cookie():141 url = "http://example.org/set_cookie"142 136- with Client(dispatch=MockDispatch()) as client:137- response = client.get(url)143+ client = Client(dispatch=MockDispatch())144+ response = await client.get(url)145 146 assert response.status_code == 200147 assert response.cookies["example-name"] == "example-value"148 assert client.cookies["example-name"] == "example-value"149 150 151+@pytest.mark.asyncio144-def test_cookie_persistence():152+async 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())157 153- 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}161 158- 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"166+167+ 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 lines4 5 import pytest6 7 from 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 )18 19 20-class MockDispatch(AsyncDispatcher):20+class 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)32 33 34+@pytest.mark.asyncio34-def test_client_header():35+async 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"}41 41- 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)44 45 assert response.status_code == 20046 assert response.json() == {47 "headers": {6 unmodified lines54 }55 }56 57 58+@pytest.mark.asyncio57-def test_header_merge():59+async 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)65 66 assert response.status_code == 20067 assert response.json() == {68 "headers": {6 unmodified lines75 }76 }77 78 79+@pytest.mark.asyncio77-def test_header_merge_conflicting_headers():80+async 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)86 87 assert response.status_code == 20088 assert response.json() == {89 "headers": {6 unmodified lines96 }97 }98 99 100+@pytest.mark.asyncio97-def test_header_update():101+async 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)109 110 assert first_response.status_code == 200111 assert first_response.json() == {112 "headers": {23 unmodified lines136 with pytest.raises(KeyError):137 del headers["baz"]138 139 140+@pytest.mark.asyncio136-def test_host_without_auth_in_header():141+async def test_host_without_auth_in_header():142 url = "http://username:password@example.org:80/echo_headers"143 139- with Client(dispatch=MockDispatch()) as client:140- response = client.get(url)144+ client = Client(dispatch=MockDispatch())145+ response = await client.get(url)146 147 assert response.status_code == 200148 assert response.json() == {149 "headers": {8 unmodified linesmodified:tests/client/test_proxies.py+4 added-4 removed
28 unmodified lines29 assert len(expected_proxies) == len(client.proxies)30 31 32 def 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 lines100 ),101 ],102 )103 def 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)107 108 if expected is None:109 assert isinstance(dispatcher, httpx.ConnectionPool)4 unmodified lines114 115 116 def 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
1 import json2 3+import pytest4+5 from 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 )15 from httpx.models import URL16 17 16-class MockDispatch(AsyncDispatcher):18+class 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)29 30 31 def test_client_queryparams():32 client = Client(params={"a": "b"})11 unmodified lines44 assert isinstance(client.params, QueryParams)45 assert client.params["a"] == "b"46 47 48+@pytest.mark.asyncio46-def test_client_queryparams_echo():49+async 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)55 56 assert response.status_code == 20057 assert response.url == URL(58 "http://example.org/echo_queryparams?first=str&second=dict"1 unmodified linemodified:tests/client/test_redirects.py+49 added-53 removed
3 unmodified lines4 import pytest5 6 from 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 )21 22 23-class MockDispatch(AsyncDispatcher):23+class 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)33 34 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)38 39 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)43 44 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)48 49 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)52 53 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)56 57 elif request.url.path == "/multiple_redirects":58 params = parse_qs(request.url.query)59 count = int(params.get("count", "0")[0])2 unmodified lines62 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)67 68 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)71 72 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)75 76 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)80 81 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)85 86 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)90 91 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)96 97 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)105 110- return AsyncResponse(codes.OK, content=b"Hello, world!", request=request)106+ return Response(codes.OK, content=b"Hello, world!", request=request)107 108 109 async 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()116 117 118 async 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) == 1124 125 126 async 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) == 1132 133 134 async 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) == 1140 141 142 async 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_OTHER8 unmodified lines156 assert len(response.history) == 1157 158 159 async 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) == 1165 166 167 async 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) == 1173 174 175 async 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) == 1181 182 183 async 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) == 207 unmodified lines196 assert len(response.history[1].history) == 1197 198 199 async 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")203 204 205 async 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()212 213 214 async 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")218 219 220 async 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()227 228 229 async 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"]236 237 238 async 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 lines247 async 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 lines260 async 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 line270 assert "content-length" not in response.json()["headers"]271 272 273 async 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"276 277 async def streaming_body():278 yield b"Example request body"2 unmodified lines281 await client.post(url, data=streaming_body())282 283 284 async 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")289 290 295-class MockCookieDispatch(AsyncDispatcher):291+class 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)305 306 elif request.url.path == "/login":307 status_code = codes.SEE_OTHER308 headers = {3 unmodified lines312 "httponly; samesite=lax"313 ),314 }315 320- return AsyncResponse(status_code, headers=headers, request=request)316+ return Response(status_code, headers=headers, request=request)317 318 elif request.url.path == "/logout":319 status_code = codes.SEE_OTHER320 headers = {2 unmodified lines323 "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)328 329 330 async def test_redirect_cookie_behavior(backend):335- client = AsyncClient(dispatch=MockCookieDispatch(), backend=backend)331+ client = Client(dispatch=MockCookieDispatch(), backend=backend)332 333 # The client is not logged in.334 response = await client.get("https://example.com/")335 assert response.url == "https://example.com/"21 unmodified linesmodified:tests/dispatch/test_http2.py+18 added-88 removed
4 unmodified lines5 import h2.events6 import pytest7 from h2.settings import SettingCodes8 9-from httpx import AsyncClient, Client, Response, Timeout9+from httpx import Client, Response, Timeout10 11 from .utils import MockHTTP2Backend12 13 8 unmodified lines22 headers = {"Content-Length": str(len(content))}23 return Response(200, headers=headers, content=content)24 25 26+@pytest.mark.asyncio26-def test_http2_get_request():27+async def test_http2_get_request():28 backend = MockHTTP2Backend(app=app)29 29- with Client(backend=backend) as client:30- response = client.get("http://example.org")31-32- assert response.status_code == 20033- assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}34-35-36-async def test_async_http2_get_request(backend):37- backend = MockHTTP2Backend(app=app, backend=backend)38-39- async with AsyncClient(backend=backend) as client:30+ async with Client(backend=backend) as client:31 response = await client.get("http://example.org")32 33 assert response.status_code == 20034 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}35 36 37+@pytest.mark.asyncio46-def test_http2_post_request():38+async def test_http2_post_request():39 backend = MockHTTP2Backend(app=app)40 49- with Client(backend=backend) as client:50- response = client.post("http://example.org", data=b"<data>")51-52- assert response.status_code == 20053- assert json.loads(response.content) == {54- "method": "POST",55- "path": "/",56- "body": "<data>",57- }58-59-60-async def test_async_http2_post_request(backend):61- backend = MockHTTP2Backend(app=app, backend=backend)62-63- 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>")43 44 assert response.status_code == 20045 assert json.loads(response.content) == {2 unmodified lines48 "body": "<data>",49 }50 51 52+@pytest.mark.asyncio74-def test_http2_large_post_request():53+async def test_http2_large_post_request():54 backend = MockHTTP2Backend(app=app)55 56 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- }86-87-88-async def test_async_http2_large_post_request(backend):89- backend = MockHTTP2Backend(app=app, backend=backend)90-91- 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 line63 "body": data.decode(),64 }65 66 67+@pytest.mark.asyncio102-def test_http2_multiple_requests():68+async def test_http2_multiple_requests():69 backend = MockHTTP2Backend(app=app)70 105- 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")109-110- assert response_1.status_code == 200111- assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}112-113- assert response_2.status_code == 200114- assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}115-116- assert response_3.status_code == 200117- assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}118-119-120-async def test_async_http2_multiple_requests(backend):121- backend = MockHTTP2Backend(app=app, backend=backend)122-123- 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 lines82 assert response_3.status_code == 20083 assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}84 85 86+@pytest.mark.asyncio138-def test_http2_reconnect():87+async 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)93 145- 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")149-150- assert response_1.status_code == 200151- assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}152-153- assert response_2.status_code == 200154- assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}155-156-157-async 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)163-164- 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 lines105 106 async def test_http2_settings_in_handshake(backend):107 backend = MockHTTP2Backend(app=app, backend=backend)108 179- async with AsyncClient(backend=backend) as client:109+ async with Client(backend=backend) as client:110 await client.get("http://example.org")111 112 h2_conn = backend.server.conn113 24 unmodified lines138 assert changed_setting.new_value == expected_settings[setting_code]139 140 141 async 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 linesdeleted:tests/dispatch/test_threaded.py-112 removed
1-import json2-3-from httpx import (4- AsyncClient,5- CertTypes,6- Client,7- Dispatcher,8- Request,9- Response,10- TimeoutTypes,11- VerifyTypes,12-)13-14-15-def streaming_body():16- for part in [b"Hello", b", ", b"world!"]:17- yield part18-19-20-class 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)39-40-41-def 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)49-50- assert response.status_code == 20051- assert response.json() == {"hello": "world"}52-53-54-async 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)62-63- assert response.status_code == 20064- assert response.json() == {"hello": "world"}65-66-67-def test_threaded_streaming_response():68- url = "https://example.org/streaming_response"69- with Client(dispatch=MockDispatch()) as client:70- response = client.get(url)71-72- assert response.status_code == 20073- assert response.text == "Hello, world!"74-75-76-def 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())80-81- assert response.status_code == 20082- assert response.text == "Hello, world!"83-84-85-def 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!")89-90- assert response.status_code == 20091- assert response.text == "Hello, world!"92-93-94-def 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!")98-99- assert response.status_code == 200100- assert response.text == "Hello, world!"101-102-103-def 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)110-111- assert response.status_code == 200112- assert response.json() == {"hello": "world"}modified:tests/models/test_requests.py+8 added-10 removed
17 unmodified lines18 assert request.headers["Content-Length"] == "8"19 20 21 def 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"25 26 27 def 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}'31 32 33 def test_transfer_encoding_header():36- def streaming_body(data):34+ async def streaming_body(data):35 yield data # pragma: nocover36 37 data = streaming_body(b"test 123")38 16 unmodified lines55 assert request.headers["Accept-Encoding"] == "identity"56 57 58 def test_override_content_length_header():61- def streaming_body(data):59+ async def streaming_body(data):60 yield data # pragma: nocover61 62 data = streaming_body(b"test 123")63 headers = {"Content-Length": "8"}25 unmodified linesmodified:tests/models/test_responses.py+22 added-76 removed
113 unmodified lines114 assert response.text == "Snowman: â\x98\x83"115 assert response.encoding == "iso-8859-1"116 117 118+@pytest.mark.asyncio118-def test_read_response():119+async def test_read_response():120 response = httpx.Response(200, content=b"Hello, world!")121 122 assert response.status_code == 200123 assert response.text == "Hello, world!"124 assert response.encoding == "ascii"125 assert response.is_closed126 126- content = response.read()127+ content = await response.read()128 129 assert content == b"Hello, world!"130 assert response.content == b"Hello, world!"131 assert response.is_closed132 133 134+@pytest.mark.asyncio133-def test_raw_interface():135+async def test_raw_interface():136 response = httpx.Response(200, content=b"Hello, world!")137 138 raw = b""137- for part in response.raw():139+ async for part in response.raw():140 raw += part141 assert raw == b"Hello, world!"142 143 144+@pytest.mark.asyncio142-def test_stream_interface():145+async def test_stream_interface():146 response = httpx.Response(200, content=b"Hello, world!")147 148 content = b""146- for part in response.stream():147- content += part148- assert content == b"Hello, world!"149-150-151-@pytest.mark.asyncio152-async def test_async_stream_interface():153- response = httpx.AsyncResponse(200, content=b"Hello, world!")154-155- content = b""149 async for part in response.stream():150 content += part151 assert content == b"Hello, world!"152 153 161-def test_stream_interface_after_read():154+@pytest.mark.asyncio155+async def test_stream_text():156 response = httpx.Response(200, content=b"Hello, world!")157 164- response.read()158+ await response.read()159 166- 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!"164 165 166 @pytest.mark.asyncio173-async def test_async_stream_interface_after_read():174- response = httpx.AsyncResponse(200, content=b"Hello, world!")167+async def test_stream_interface_after_read():168+ response = httpx.Response(200, content=b"Hello, world!")169 170 await response.read()171 172 content = b""1 unmodified line174 content += part175 assert content == b"Hello, world!"176 177 184-def test_streaming_response():185- response = httpx.Response(200, content=streaming_body())186-187- assert response.status_code == 200188- assert not response.is_closed189-190- content = response.read()191-192- assert content == b"Hello, world!"193- assert response.content == b"Hello, world!"194- assert response.is_closed195-196-178 @pytest.mark.asyncio198-async def test_async_streaming_response():199- response = httpx.AsyncResponse(200, content=async_streaming_body())179+async def test_streaming_response():180+ response = httpx.Response(200, content=async_streaming_body())181 182 assert response.status_code == 200183 assert not response.is_closed184 3 unmodified lines188 assert response.content == b"Hello, world!"189 assert response.is_closed190 191 211-def test_cannot_read_after_stream_consumed():212- response = httpx.Response(200, content=streaming_body())213-214- content = b""215- for part in response.stream():216- content += part217-218- with pytest.raises(httpx.StreamConsumed):219- response.read()220-221-192 @pytest.mark.asyncio223-async def test_async_cannot_read_after_stream_consumed():224- response = httpx.AsyncResponse(200, content=async_streaming_body())193+async def test_cannot_read_after_stream_consumed():194+ response = httpx.Response(200, content=async_streaming_body())195 196 content = b""197 async for part in response.stream():198 content += part1 unmodified line200 with pytest.raises(httpx.StreamConsumed):201 await response.read()202 203 234-def test_cannot_read_after_response_closed():235- response = httpx.Response(200, content=streaming_body())236-237- response.close()238-239- with pytest.raises(httpx.ResponseClosed):240- response.read()241-242-204 @pytest.mark.asyncio244-async def test_async_cannot_read_after_response_closed():245- response = httpx.AsyncResponse(200, content=async_streaming_body())205+async def test_cannot_read_after_response_closed():206+ response = httpx.Response(200, content=async_streaming_body())207 208 await response.close()209 210 with pytest.raises(httpx.ResponseClosed):60 unmodified lines271 )272 def test_link_headers(headers, expected):273 response = httpx.Response(200, content=None, headers=headers)274 assert response.links == expected314-315-316-@pytest.mark.asyncio317-async def test_stream_text():318- async def iterator():319- yield b"Hello, world!"320-321- response = httpx.AsyncResponse(200, content=iterator().__aiter__())322-323- await response.read()324-325- 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
1-import sys2-3-import pytest4-5-import httpx6-7-8-def 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"] = httpx12-13-14-@pytest.fixture(autouse=True)15-def 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."""2-import pytest3-import requests4-5-6-@pytest.mark.copied_from(7- "https://github.com/psf/requests/blob/v2.22.0/tests/test_requests.py#L61-L70"8-)9-def test_entrypoints():10- requests.session11- requests.session().get12- requests.session().head13- requests.get14- requests.head15- requests.put16- requests.patch17- requests.post18-19-20-@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-)27-def test_poolmanager_entrypoint():28- # Not really an entry point, but people rely on it.29- from requests.packages.urllib3.poolmanager import PoolManager # noqa: F401modified:tests/conftest.py+1 added-5 removed
161 unmodified lines162 163 164 async 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"})169 170 166 unmodified linesmodified:tests/test_api.py+28 added-19 removed
1 unmodified line2 3 import httpx4 5 6+@pytest.mark.asyncio6-def test_get(server):7- response = httpx.get(server.url)7+async 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"13 14 15+@pytest.mark.asyncio14-def test_post(server):15- response = httpx.post(server.url, data=b"Hello, world!")16+async 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"20 21 22+@pytest.mark.asyncio20-def test_post_byte_iterator(server):21- def data():23+async def test_post_byte_iterator(server):24+ async def data():25 yield b"Hello"26 yield b", "27 yield b"world!"28 26- 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"32 33 34+@pytest.mark.asyncio31-def test_options(server):32- response = httpx.options(server.url)35+async def test_options(server):36+ response = await httpx.options(server.url)37 assert response.status_code == 20038 assert response.reason_phrase == "OK"39 40 41+@pytest.mark.asyncio37-def test_head(server):38- response = httpx.head(server.url)42+async def test_head(server):43+ response = await httpx.head(server.url)44 assert response.status_code == 20045 assert response.reason_phrase == "OK"46 47 48+@pytest.mark.asyncio43-def test_put(server):44- response = httpx.put(server.url, data=b"Hello, world!")49+async 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"53 54 55+@pytest.mark.asyncio49-def test_patch(server):50- response = httpx.patch(server.url, data=b"Hello, world!")56+async 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"60 61 62+@pytest.mark.asyncio55-def test_delete(server):56- response = httpx.delete(server.url)63+async def test_delete(server):64+ response = await httpx.delete(server.url)65 assert response.status_code == 20066 assert response.reason_phrase == "OK"67 68 69+@pytest.mark.asyncio61-def test_get_invalid_url(server):70+async 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 lines38 await send({"type": "http.response.body", "body": output})39 raise ValueError()40 41 42+@pytest.mark.asyncio42-def test_asgi():43+async 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!"47-48-49-async 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!"48 49 50+@pytest.mark.asyncio56-def test_asgi_upload():51+async 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"61-62-63-async 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"56 57 58+@pytest.mark.asyncio70-def test_asgi_exc():59+async def test_asgi_exc():60 client = httpx.Client(app=raise_exc)61 with pytest.raises(ValueError):73- client.get("http://www.example.org/")74-75-76-async 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/")63 64 65+@pytest.mark.asyncio82-def test_asgi_exc_after_response():66+async 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/")86-87-88-async 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 lines70 response = httpx.Response(200, headers=headers, content=compressed_body)71 assert response.content == body72 73 74+@pytest.mark.asyncio74-def test_streaming():75+async def test_streaming():76 body = b"test 123"77 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)78 78- def compress(body):79+ async def compress(body):80 yield compressor.compress(body)81 yield compressor.flush()82 83 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() == body87 88 89 @pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br", b"identity"))90 def test_empty_content(header_value):37 unmodified lines128 "euc-jp",129 ),130 ],131 )132+@pytest.mark.asyncio131-def test_text_decoder(data, encoding):132- def iterator():133+async def test_text_decoder(data, encoding):134+ async def iterator():135 nonlocal data136 for chunk in data:137 yield chunk138 139 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)142 143 144+@pytest.mark.asyncio141-def test_text_decoder_known_encoding():142- def iterator():145+async 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 lines153 headers=[(b"Content-Type", b"text/html; charset=shift-jis")],154 content=iterator(),155 )156 157+ await response.read()153- assert "".join(response.stream_text()) == "トラベル"158+ assert "".join(response.text) == "トラベル"159 160 161 def test_text_decoder_empty_cases():162 decoder = TextDecoder()8 unmodified lines171 headers = [(b"Content-Encoding", b"invalid-header")]172 body = b"test 123"173 174 response = httpx.Response(200, headers=headers, content=body)170-171- assert response.read() == body175+ assert response.content == bodymodified:tests/test_multipart.py+15 added-10 removed
18 unmodified lines19 )20 21 22 class 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)33 34 35 @pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))36+@pytest.mark.asyncio35-def test_multipart(value, output):37+async def test_multipart(value, output):38 client = Client(dispatch=MockDispatch())39 40 # 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 == 20045 46 # 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 lines56 assert multipart["file"] == [b"<file content>"]57 58 59 @pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))60+@pytest.mark.asyncio58-def test_multipart_invalid_key(key):61+async 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)68 69 70 @pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))71+@pytest.mark.asyncio68-def test_multipart_invalid_value(value):72+async 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)79 80 81+@pytest.mark.asyncio77-def test_multipart_file_tuple():82+async def test_multipart_file_tuple():83 client = Client(dispatch=MockDispatch())84 85 # 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 == 20090 91 # 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 linesmodified:tests/test_timeouts.py+4 added-15 removed
1 import pytest2 3 from httpx import (4- AsyncClient,4 Client,5 ConnectTimeout,6 PoolLimits,7 PoolTimeout,5 unmodified lines13 14 async def test_read_timeout(server, backend):15 timeout = TimeoutConfig(read_timeout=1e-6)16 18- 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"))20 21 22 async def test_write_timeout(server, backend):23 timeout = TimeoutConfig(write_timeout=1e-6)24 26- 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)29 30 31 async def test_connect_timeout(server, backend):32 timeout = TimeoutConfig(connect_timeout=1e-6)33 35- 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/")38 39 40 async def test_pool_timeout(server, backend):41 pool_limits = PoolLimits(hard_limit=1, pool_timeout=1e-4)42 44- 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)45 46 with pytest.raises(PoolTimeout):47 await client.get("http://localhost:8000/")48 49 await response.read()51-52-53-def test_sync_infinite_timeout(server):54- """Regression test for a bug that occurred under Python 3.6.55-56- 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 lines103 104 @pytest.mark.asyncio105 async 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 stderr2 unmodified lines114 115 @pytest.mark.asyncio116 async 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 stderr2 unmodified lines125 126 @pytest.mark.asyncio127 async 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 == 200132 133 stderr = capsys.readouterr().err.strip()165 unmodified linesdeleted:tests/test_wsgi.py-95 removed
1-import sys2-3-import pytest4-5-import httpx6-7-8-def hello_world(environ, start_response):9- status = "200 OK"10- output = b"Hello, World!"11-12- response_headers = [13- ("Content-type", "text/plain"),14- ("Content-Length", str(len(output))),15- ]16-17- start_response(status, response_headers)18-19- return [output]20-21-22-def echo_body(environ, start_response):23- status = "200 OK"24- output = environ["wsgi.input"].read()25-26- response_headers = [27- ("Content-type", "text/plain"),28- ("Content-Length", str(len(output))),29- ]30-31- start_response(status, response_headers)32-33- return [output]34-35-36-def echo_body_with_response_stream(environ, start_response):37- status = "200 OK"38-39- response_headers = [("Content-Type", "text/plain")]40-41- start_response(status, response_headers)42-43- def output_generator(f):44- while True:45- output = f.read(2)46- if not output:47- break48- yield output49-50- return output_generator(f=environ["wsgi.input"])51-52-53-def raise_exc(environ, start_response):54- status = "500 Server Error"55- output = b"Nope!"56-57- response_headers = [58- ("Content-type", "text/plain"),59- ("Content-Length", str(len(output))),60- ]61-62- try:63- raise ValueError()64- except ValueError:65- exc_info = sys.exc_info()66- start_response(status, response_headers, exc_info=exc_info)67-68- return [output]69-70-71-def 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!"76-77-78-def 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"83-84-85-def 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"90-91-92-def 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 lines12 - 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 linesmodified:README.md+18 added-10 removed
14 unmodified lines15 <img src="https://badge.fury.io/py/httpx.svg" alt="Package version">16 </a>17 </p>18 19-**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.*19+HTTPX is an asynchronous HTTP client, that supports HTTP/2 and HTTP/1.1.20 21+It can be used in high-performance async web frameworks, using either asyncio22+or trio, and is able to support making large numbers of requests concurrently.23+24+**Note**: *The 0.8 release switched HTTPX into focusing exclusively on the async25+client. It is possible that we'll look at re-introducing a sync API at a26+later date.*27+28 ---29 30 Let's get started...31 32+*The standard Python REPL does not allow top-level async statements.*33+34+*To run async examples directly you'll probably want to either use `ipython`,35+or use Python 3.8 with `python -m asyncio`.*36+37 ```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_code43 2008 unmodified lines52 ## Features53 54 HTTPX builds on the well-established usability of `requests`, and gives you:55 44-* 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 lines71 * 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 Requests13 unmodified lines93 Project documentation is available at [www.encode.io/httpx/](https://www.encode.io/httpx/).94 95 For a run-through of all the basics, head over to the [QuickStart](https://www.encode.io/httpx/quickstart/).96 87-For more advanced topics, see the [Advanced Usage](https://www.encode.io/httpx/advanced/) section, or88-the specific topics on making [Parallel Requests](https://www.encode.io/httpx/parallel/) or using the89-[Async Client](https://www.encode.io/httpx/async/).97+For more advanced topics, see the [Advanced Usage](https://www.encode.io/httpx/advanced/) section.98 99 The [Developer Interface](https://www.encode.io/httpx/api/) provides a comprehensive API reference.100 101 ## Contribute22 unmodified lines