Use pycon for Python console code blocks (#1187)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Hugo van Kemenade · committed by GitHub · parent 9fa95cc · Browse files · 6 files·+70 added−70 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Florimond Manca <florimond.manca@gmail.com>
Diff stats
6 files+70 added−70 removed
- other:+70 added−70 removed
Provenance
- Commit
d10b7cd- Tree
37c3fb5- Author
Hugo van Kemenade <hugovk@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
9fa95cc
6 files changed+70 added−70 removed
modified:docs/advanced.md+18 added-18 removed
54 unmodified lines55 ### Making requests56 57 Once you have a `Client`, you can send requests using `.get()`, `.post()`, etc. For example:58 59-```python59+```pycon60 >>> with httpx.Client() as client:61 ... r = client.get('https://example.com')62 ...63 >>> r3 unmodified lines67 These methods accept the same arguments as `httpx.get()`, `httpx.post()`, etc. This means that all features documented in the [Quickstart](/quickstart) guide are also available at the client level.68 69 For example, to send a request with custom headers:70 71-```python71+```pycon72 >>> with httpx.Client() as client:73 ... headers = {'X-Custom': 'value'}74 ... r = client.get('https://example.com', headers=headers)75 ...6 unmodified lines82 Clients allow you to apply configuration to all outgoing requests by passing parameters to the `Client` constructor.83 84 For example, to apply a set of custom headers _on every request_:85 86-```python86+```pycon87 >>> url = 'http://httpbin.org/headers'88 >>> headers = {'user-agent': 'my-app/0.0.1'}89 >>> with httpx.Client(headers=headers) as client:90 ... r = client.get(url)7 unmodified lines98 When a configuration option is provided at both the client-level and request-level, one of two things can happen:99 100 - For headers, query parameters and cookies, the values are combined together. For example:101 102-```python102+```pycon103 >>> headers = {'X-Auth': 'from-client'}104 >>> params = {'client_id': 'client1'}105 >>> with httpx.Client(headers=headers, params=params) as client:106 ... headers = {'X-Custom': 'from-request'}9 unmodified lines116 ```117 118 - For all other parameters, the request-level value takes priority. For example:119 120-```python120+```pycon121 >>> with httpx.Client(auth=('tom', 'mot123')) as client:122 ... r = client.get('https://example.com', auth=('alice', 'ecila123'))123 ...124 >>> _, _, auth = r.request.headers['Authorization'].partition(' ')9 unmodified lines134 Additionally, `Client` accepts some configuration options that aren't available at the request level.135 136 For example, `base_url` allows you to prepend an URL to all outgoing requests:137 138-```python138+```pycon139 >>> with httpx.Client(base_url='http://httpbin.org') as client:140 ... r = client.get('/headers')141 ...142 >>> r.request.url88 unmodified lines231 If you need to refresh the cache (e.g. because the NETRC file has changed),232 you should create a new client or restart the interpreter.233 234 As default `trust_env` is true. To set false:235-```python235+```pycon236 >>> httpx.get('https://example.org/', trust_env=False)237 ```238 239 If `NETRC` environment is empty, HTTPX tries to use default files.240 (`~/.netrc`, `~/_netrc`)241 242 To change `NETRC` environment:243-```python243+```pycon244 >>> import os245 >>> os.environ["NETRC"] = "my_default_folder/.my_netrc"246 ```247 323 unmodified lines571 As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)572 multipart file encoding is available by passing a dictionary with the573 name of the payloads as keys and either tuple of elements or a file-like object or a string as values.574 575-```python575+```pycon576 >>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}577 >>> r = httpx.post("https://httpbin.org/post", files=files)578 >>> print(r.text)579 {16 unmodified lines596 on the file name, with unknown file extensions defaulting to "application/octet-stream".597 If the file name is explicitly set to `None` then HTTPX will not include a content-type598 MIME header field.599 600-```python600+```pycon601 >>> files = {'upload-file': (None, 'text content', 'text/plain')}602 >>> r = httpx.post("https://httpbin.org/post", files=files)603 >>> print(r.text)604 {14 unmodified lines619 You can also send multiple files in one go with a multiple file field form.620 To do that, pass a list of `(field, <file>)` items instead of a dictionary, allowing you to pass multiple items with the same `field`.621 For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field:622 623-```python623+```pycon624 >>> files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),625 ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]626 >>> r = httpx.post("https://httpbin.org/post", files=files)627 ```113 unmodified lines741 ```742 743 Alternatively, you can pass a standard library `ssl.SSLContext`.744 745-```python745+```pycon746 >>> import ssl747 >>> import httpx748 >>> context = ssl.create_default_context()749 >>> context.load_verify_locations(cafile="/tmp/client.pem")2 unmodified lines752 ```753 754 We also include a helper function for creating properly configured `SSLContext` instances.755 756-```python756+```pycon757 >>> context = httpx.create_ssl_context()758 ```759 760 The `create_ssl_context` function accepts the same set of SSL configuration arguments761 (`trust_env`, `verify`, `cert` and `http2` arguments)762 as `httpx.Client` or `httpx.AsyncClient`763 764-```python764+```pycon765 >>> import httpx766 >>> context = httpx.create_ssl_context(verify="/tmp/client.pem")767 >>> httpx.get('https://example.org', verify=context)768 <Response [200 OK]>26 unmodified lines795 1. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.796 1. Pass the server key/cert files when starting your local server. (This depends on the particular web server you're using. For example, [Uvicorn](https://www.uvicorn.org) provides the `--ssl-keyfile` and `--ssl-certfile` options.)797 1. Tell HTTPX to use the certificates stored in `client.pem`:798 799-```python799+```pycon800 >>> import httpx801 >>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")802 >>> r803 Response <200 OK>9 unmodified lines813 class directly, and pass it to the client instance. The `httpcore` package814 provides a `local_address` configuration that is only available via this815 low-level API.816 817-```python817+```pycon818 >>> import httpx, httpcore819 >>> ssl_context = httpx.create_ssl_context()820 >>> transport = httpcore.SyncConnectionPool(821 ... ssl_context=ssl_context,31 unmodified lines853 HTTPX also currently ships with a transport that uses the excellent854 [`urllib3` library](https://urllib3.readthedocs.io/en/latest/), which can be855 used with the sync `Client`...856 857-```python857+```pycon858 >>> import httpx859 >>> client = httpx.Client(transport=httpx.URLLib3Transport())860 >>> client.get("https://example.org")861 <Response [200 OK]>28 unmodified lines890 ```891 892 Which we can use in the same way:893 894-```python894+```pycon895 >>> import httpx896 >>> client = httpx.Client(transport=HelloWorldTransport())897 >>> response = client.get("https://example.org/")898 >>> response.json()2 unmodified linesmodified:docs/api.md+4 added-4 removed
86 unmodified lines878889909191929394957 unmodified lines10310410510610710710810911011115 unmodified lines1271281291301311311321331341354 unmodified lines1401411421431441441451461471489 unmodified lines86 unmodified lines
*An HTTP request. Can be constructed explicitly for more control over exactlywhat gets sent over the wire.*
```python```pycon>>> request = httpx.Request("GET", "https://example.org", headers={'host': 'example.org'})>>> response = client.send(request)```
7 unmodified lines## `URL`
*A normalized, IDNA supporting URL.*
```python```pycon>>> url = URL("https://example.org/")>>> url.host'example.org'```15 unmodified lines## `Headers`
*A case-insensitive multi-dict.*
```python```pycon>>> headers = Headers({'Content-Type': 'application/json'})>>> headers['content-type']'application/json'```4 unmodified lines## `Cookies`
*A dict-like cookie store.*
```python```pycon>>> cookies = Cookies()>>> cookies.set("name", "value", domain="example.org")```
9 unmodified linesmodified:docs/async.md+3 added-3 removed
12 unmodified lines13 ## Making Async requests14 15 To make asynchronous requests, you'll need an `AsyncClient`.16 17-```python17+```pycon18 >>> async with httpx.AsyncClient() as client:19 >>> r = await client.get('https://www.example.com/')20 >>> r21 <Response [200 OK]>41 unmodified lines63 ### Streaming responses64 65 The `AsyncClient.stream(method, url, ...)` method is an async context block.66 67-```python67+```pycon68 >>> client = httpx.AsyncClient()69 >>> async with client.stream('GET', 'https://www.example.com/') as response:70 >>> async for chunk in response.aiter_bytes():71 >>> ...104 unmodified lines176 ```177 178 We can make requests directly against the application, like so:179 180-```python180+```pycon181 >>> import httpx182 >>> async with httpx.AsyncClient(app=app, base_url="http://testserver") as client:183 ... r = await client.get("/")184 ... assert r.status_code == 20020 unmodified linesmodified:docs/index.md+2 added-2 removed
33 unmodified lines34 ---35 36 Let's get started...37 38-```python38+```pycon39 >>> import httpx40 >>> r = httpx.get('https://www.example.org/')41 >>> r42 <Response [200 OK]>8 unmodified lines51 Or, using the async API...52 53 _Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.8+ with `python -m asyncio` to try this code interactively._54 55-```python55+```pycon56 >>> import httpx57 >>> async with httpx.AsyncClient() as client:58 >>> r = await client.get('https://www.example.org/')59 >>> r81 unmodified linesmodified:docs/quickstart.md+41 added-41 removed
1 # QuickStart2 3 First, start by importing HTTPX:4 5-```python5+```pycon6 >>> import httpx7 ```8 9 Now, let’s try to get a webpage.10 11-```python11+```pycon12 >>> r = httpx.get('https://httpbin.org/get')13 >>> r14 <Response [200 OK]>15 ```16 17 Similarly, to make an HTTP POST request:18 19-```python19+```pycon20 >>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})21 ```22 23 The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:24 25-```python25+```pycon26 >>> r = httpx.put('https://httpbin.org/put', data={'key': 'value'})27 >>> r = httpx.delete('https://httpbin.org/delete')28 >>> r = httpx.head('https://httpbin.org/get')29 >>> r = httpx.options('https://httpbin.org/get')2 unmodified lines32 ## Passing Parameters in URLs33 34 To include URL query parameters in the request, use the `params` keyword:35 36-```python36+```pycon37 >>> params = {'key1': 'value1', 'key2': 'value2'}38 >>> r = httpx.get('https://httpbin.org/get', params=params)39 ```40 41 To see how the values get encoding into the URL string, we can inspect the42 resulting URL that was used to make the request:43 44-```python44+```pycon45 >>> r.url46 URL('https://httpbin.org/get?key2=value2&key1=value1')47 ```48 49 You can also pass a list of items as a value:50 51-```python51+```pycon52 >>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}53 >>> r = httpx.get('https://httpbin.org/get', params=params)54 >>> r.url55 URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')2 unmodified lines58 ## Response Content59 60 HTTPX will automatically handle decoding the response content into Unicode text.61 62-```python62+```pycon63 >>> r = httpx.get('https://www.example.org/')64 >>> r.text65 '<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'66 ```67 68 You can inspect what encoding has been used to decode the response.69 70-```python70+```pycon71 >>> r.encoding72 'UTF-8'73 ```74 75 If you need to override the standard behavior and explicitly set the encoding to76 use, then you can do that too.77 78-```python78+```pycon79 >>> r.encoding = 'ISO-8859-1'80 ```81 82 ## Binary Response Content83 84 The response content can also be accessed as bytes, for non-text responses:85 86-```python86+```pycon87 >>> r.content88 b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'89 ```90 2 unmodified lines93 encoding will also be supported.94 95 For example, to create an image from binary data returned by a request, you can use the following code:96 97-```python97+```pycon98 >>> from PIL import Image99 >>> from io import BytesIO100 >>> i = Image.open(BytesIO(r.content))101 ```1 unmodified line103 ## JSON Response Content104 105 Often Web API responses will be encoded as JSON.106 107-```python107+```pycon108 >>> r = httpx.get('https://api.github.com/events')109 >>> r.json()110 [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...' ... }}]111 ```1 unmodified line113 ## Custom Headers114 115 To include additional headers in the outgoing request, use the `headers` keyword argument:116 117-```python117+```pycon118 >>> url = 'http://httpbin.org/headers'119 >>> headers = {'user-agent': 'my-app/0.0.1'}120 >>> r = httpx.get(url, headers=headers)121 ```3 unmodified lines125 Some types of HTTP requests, such as `POST` and `PUT` requests, can include data126 in the request body. One common way of including that is as form-encoded data,127 which is used for HTML forms.128 129-```python129+```pycon130 >>> data = {'key1': 'value1', 'key2': 'value2'}131 >>> r = httpx.post("https://httpbin.org/post", data=data)132 >>> print(r.text)133 {7 unmodified lines141 ```142 143 Form encoded data can also include multiple values from a given key.144 145-```python145+```pycon146 >>> data = {'key1': ['value1', 'value2']}147 >>> r = httpx.post("https://httpbin.org/post", data=data)148 >>> print(r.text)149 {11 unmodified lines161 ## Sending Multipart File Uploads162 163 You can also upload files, using HTTP multipart encoding:164 165-```python165+```pycon166 >>> files = {'upload-file': open('report.xls', 'rb')}167 >>> r = httpx.post("https://httpbin.org/post", files=files)168 >>> print(r.text)169 {7 unmodified lines177 178 You can also explicitly set the filename and content type, by using a tuple179 of items for the file value:180 181-```python181+```pycon182 >>> files = {'upload-file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel')}183 >>> r = httpx.post("https://httpbin.org/post", files=files)184 >>> print(r.text)185 {6 unmodified lines192 ```193 194 If you need to include non-file data fields in the multipart form, use the `data=...` parameter:195 196-```python196+```pycon197 >>> data = {'message': 'Hello, world!'}198 >>> files = {'file': open('report.xls', 'rb')}199 >>> r = httpx.post("https://httpbin.org/post", data=data, files=files)200 >>> print(r.text)13 unmodified lines214 215 Form encoded data is okay if all you need is a simple key-value data structure.216 For more complicated data structures you'll often want to use JSON encoding instead.217 218-```python218+```pycon219 >>> data = {'integer': 123, 'boolean': True, 'list': ['a', 'b', 'c']}220 >>> r = httpx.post("https://httpbin.org/post", json=data)221 >>> print(r.text)222 {22 unmodified lines245 ## Response Status Codes246 247 We can inspect the HTTP status code of the response:248 249-```python249+```pycon250 >>> r = httpx.get('https://httpbin.org/get')251 >>> r.status_code252 200253 ```254 255 HTTPX also includes an easy shortcut for accessing status codes by their text phrase.256 257-```python257+```pycon258 >>> r.status_code == httpx.codes.OK259 True260 ```261 262 We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):263 264-```python264+```pycon265 >>> not_found = httpx.get('https://httpbin.org/status/404')266 >>> not_found.status_code267 404268 >>> not_found.raise_for_status()5 unmodified lines274 ```275 276 Any successful response codes will simply return `None` rather than raising an exception.277 278-```python278+```pycon279 >>> r.raise_for_status()280 ```281 282 ## Response Headers283 284 The response headers are available as a dictionary-like interface.285 286-```python286+```pycon287 >>> r.headers288 Headers({289 'content-encoding': 'gzip',290 'transfer-encoding': 'chunked',6 unmodified lines297 ```298 299 The `Headers` data type is case-insensitive, so you can use any capitalization.300 301-```python301+```pycon302 >>> r.headers['Content-Type']303 'application/json'304 305 >>> r.headers.get('content-type')9 unmodified lines315 For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.316 317 You can stream the binary content of the response...318 319-```python319+```pycon320 >>> with httpx.stream("GET", "https://www.example.com") as r:321 ... for data in r.iter_bytes():322 ... print(data)323 ```324 325 Or the text of the response...326 327-```python327+```pycon328 >>> with httpx.stream("GET", "https://www.example.com") as r:329 ... for text in r.iter_text():330 ... print(text)331 ```332 333 Or stream the text, on a line-by-line basis...334 335-```python335+```pycon336 >>> with httpx.stream("GET", "https://www.example.com") as r:337 ... for line in r.iter_lines():338 ... print(line)339 ```1 unmodified line341 HTTPX will use universal line endings, normalising all cases to `\n`.342 343 In some cases you might want to access the raw bytes on the response without applying any HTTP content decoding. In this case any content encoding that the web server has applied such as `gzip`, `deflate`, or `brotli` will not be automatically decoded.344 345-```python345+```pycon346 >>> with httpx.stream("GET", "https://www.example.com") as r:347 ... for chunk in r.iter_raw():348 ... print(chunk)349 ```350 351 If you're using streaming responses in any of these ways then the `response.content` and `response.text` attributes will not be available, and will raise errors if accessed. However you can also use the response streaming functionality to conditionally load the response body:352 353-```python353+```pycon354 >>> with httpx.stream("GET", "https://www.example.com") as r:355 ... if r.headers['Content-Length'] < TOO_LONG:356 ... r.read()357 ... print(r.text)2 unmodified lines360 ## Cookies361 362 Any cookies that are set on the response can be easily accessed:363 364-```python364+```pycon365 >>> r = httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)366 >>> r.cookies['chocolate']367 'chip'368 ```369 370 To include cookies in an outgoing request, use the `cookies` parameter:371 372-```python372+```pycon373 >>> cookies = {"peanut": "butter"}374 >>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)375 >>> r.json()376 {'cookies': {'peanut': 'butter'}}1 unmodified line378 379 Cookies are returned in a `Cookies` instance, which is a dict-like data structure380 with additional API for accessing cookies by their domain or path.381 382-```python382+```pycon383 >>> cookies = httpx.Cookies()384 >>> cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')385 >>> cookies.set('cookie_off_domain', 'nope.', domain='example.org')386 >>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)10 unmodified lines397 in which they were made.398 399 For example, GitHub redirects all HTTP requests to HTTPS.400 401-```python401+```pycon402 >>> r = httpx.get('http://github.com/')403 >>> r.url404 URL('https://github.com/')405 >>> r.status_code3 unmodified lines409 ```410 411 You can modify the default redirection handling with the allow_redirects parameter:412 413-```python413+```pycon414 >>> r = httpx.get('http://github.com/', allow_redirects=False)415 >>> r.status_code416 301417 >>> r.history1 unmodified line419 ```420 421 If you’re making a `HEAD` request, you can use this to enable redirection:422 423-```python423+```pycon424 >>> r = httpx.head('http://github.com/', allow_redirects=True)425 >>> r.url426 'https://github.com/'427 >>> r.history8 unmodified lines436 437 The default timeout for network inactivity is five seconds. You can modify the438 value to be more or less strict:439 440-```python440+```pycon441 >>> httpx.get('https://github.com/', timeout=0.001)442 ```443 444 You can also disable the timeout behavior completely...445 446-```python446+```pycon447 >>> httpx.get('https://github.com/', timeout=None)448 ```449 450 For advanced timeout management, see [Timeout fine-tuning](advanced.md#fine-tuning-the-configuration).5 unmodified lines456 To provide Basic authentication credentials, pass a 2-tuple of457 plaintext `str` or `bytes` objects as the `auth` argument to the request458 functions:459 460-```python460+```pycon461 >>> httpx.get("https://example.com", auth=("my_user", "password123"))462 ```463 464 To provide credentials for Digest authentication you'll need to instantiate465 a `DigestAuth` object with the plaintext username and password as arguments.466 This object can be then passed as the `auth` argument to the request methods467 as above:468 469-```python469+```pycon470 >>> auth = httpx.DigestAuth("my_user", "password123")471 >>> httpx.get("https://example.com", auth=auth)472 <Response [200 OK]>473 ```modified:README.md+2 added-2 removed
21 unmodified lines22 ---23 24 Let's get started...25 26-```python26+```pycon27 >>> import httpx28 >>> r = httpx.get('https://www.example.org/')29 >>> r30 <Response [200 OK]>8 unmodified lines39 Or, using the async API...40 41 _Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.8+ with `python -m asyncio` to try this code interactively._42 43-```python43+```pycon44 >>> import httpx45 >>> async with httpx.AsyncClient() as client:46 >>> r = await client.get('https://www.example.org/')47 >>> r86 unmodified lines