Skip to content
Myr

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

6 files+70 added−70 removed

modified:docs/advanced.md+18 added-18 removed
54 unmodified lines
55### Making requests5657Once you have a `Client`, you can send requests using `.get()`, `.post()`, etc. For example:5859```python59```pycon60>>> with httpx.Client() as client:61... r = client.get('https://example.com')62...63>>> r
3 unmodified lines
67These 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.6869For example, to send a request with custom headers:7071```python71```pycon72>>> with httpx.Client() as client:73... headers = {'X-Custom': 'value'}74... r = client.get('https://example.com', headers=headers)75...
6 unmodified lines
82Clients allow you to apply configuration to all outgoing requests by passing parameters to the `Client` constructor.8384For example, to apply a set of custom headers _on every request_:8586```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 lines
98When a configuration option is provided at both the client-level and request-level, one of two things can happen:99100- For headers, query parameters and cookies, the values are combined together. For example:101102```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 lines
116```117118- For all other parameters, the request-level value takes priority. For example:119120```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 lines
134Additionally, `Client` accepts some configuration options that aren't available at the request level.135136For example, `base_url` allows you to prepend an URL to all outgoing requests:137138```python138```pycon139>>> with httpx.Client(base_url='http://httpbin.org') as client:140... r = client.get('/headers')141...142>>> r.request.url
88 unmodified lines
231 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.233234As default `trust_env` is true. To set false:235```python235```pycon236>>> httpx.get('https://example.org/', trust_env=False)237```238239If `NETRC` environment is empty, HTTPX tries to use default files.240(`~/.netrc`, `~/_netrc`)241242To change `NETRC` environment:243```python243```pycon244>>> import os245>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"246```247
323 unmodified lines
571As mentioned in the [quickstart](/quickstart#sending-multipart-file-uploads)572multipart file encoding is available by passing a dictionary with the573name of the payloads as keys and either tuple of elements or a file-like object or a string as values.574575```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 lines
596on the file name, with unknown file extensions defaulting to "application/octet-stream".597If the file name is explicitly set to `None` then HTTPX will not include a content-type598MIME header field.599600```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 lines
619You can also send multiple files in one go with a multiple file field form.620To do that, pass a list of `(field, <file>)` items instead of a dictionary, allowing you to pass multiple items with the same `field`.621For instance this request sends 2 files, `foo.png` and `bar.png` in one request on the `images` form field:622623```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 lines
741```742743Alternatively, you can pass a standard library `ssl.SSLContext`.744745```python745```pycon746>>> import ssl747>>> import httpx748>>> context = ssl.create_default_context()749>>> context.load_verify_locations(cafile="/tmp/client.pem")
2 unmodified lines
752```753754We also include a helper function for creating properly configured `SSLContext` instances.755756```python756```pycon757>>> context = httpx.create_ssl_context()758```759760The `create_ssl_context` function accepts the same set of SSL configuration arguments761(`trust_env`, `verify`, `cert` and `http2` arguments)762as `httpx.Client` or `httpx.AsyncClient`763764```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 lines
7951. Use [trustme-cli](https://github.com/sethmlarson/trustme-cli/) to generate a pair of server key/cert files, and a client cert file.7961. 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.)7971. Tell HTTPX to use the certificates stored in `client.pem`:798799```python799```pycon800>>> import httpx801>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")802>>> r803Response <200 OK>
9 unmodified lines
813class directly, and pass it to the client instance. The `httpcore` package814provides a `local_address` configuration that is only available via this815low-level API.816817```python817```pycon818>>> import httpx, httpcore819>>> ssl_context = httpx.create_ssl_context()820>>> transport = httpcore.SyncConnectionPool(821... ssl_context=ssl_context,
31 unmodified lines
853HTTPX also currently ships with a transport that uses the excellent854[`urllib3` library](https://urllib3.readthedocs.io/en/latest/), which can be855used with the sync `Client`...856857```python857```pycon858>>> import httpx859>>> client = httpx.Client(transport=httpx.URLLib3Transport())860>>> client.get("https://example.org")861<Response [200 OK]>
28 unmodified lines
890```891892Which we can use in the same way:893894```python894```pycon895>>> import httpx896>>> client = httpx.Client(transport=HelloWorldTransport())897>>> response = client.get("https://example.org/")898>>> response.json()
2 unmodified lines
modified:docs/api.md+4 added-4 removed
modified:docs/async.md+3 added-3 removed
12 unmodified lines
13## Making Async requests1415To make asynchronous requests, you'll need an `AsyncClient`.1617```python17```pycon18>>> async with httpx.AsyncClient() as client:19>>> r = await client.get('https://www.example.com/')20>>> r21<Response [200 OK]>
41 unmodified lines
63### Streaming responses6465The `AsyncClient.stream(method, url, ...)` method is an async context block.6667```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 lines
176```177178We can make requests directly against the application, like so:179180```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 == 200
20 unmodified lines
modified:docs/index.md+2 added-2 removed
33 unmodified lines
34---3536Let's get started...3738```python38```pycon39>>> import httpx40>>> r = httpx.get('https://www.example.org/')41>>> r42<Response [200 OK]>
8 unmodified lines
51Or, using the async API...5253_Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.8+ with `python -m asyncio` to try this code interactively._5455```python55```pycon56>>> import httpx57>>> async with httpx.AsyncClient() as client:58>>> r = await client.get('https://www.example.org/')59>>> r
81 unmodified lines
modified:docs/quickstart.md+41 added-41 removed
1# QuickStart23First, start by importing HTTPX:45```python5```pycon6>>> import httpx7```89Now, let’s try to get a webpage.1011```python11```pycon12>>> r = httpx.get('https://httpbin.org/get')13>>> r14<Response [200 OK]>15```1617Similarly, to make an HTTP POST request:1819```python19```pycon20>>> r = httpx.post('https://httpbin.org/post', data={'key': 'value'})21```2223The PUT, DELETE, HEAD, and OPTIONS requests all follow the same style:2425```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 lines
32## Passing Parameters in URLs3334To include URL query parameters in the request, use the `params` keyword:3536```python36```pycon37>>> params = {'key1': 'value1', 'key2': 'value2'}38>>> r = httpx.get('https://httpbin.org/get', params=params)39```4041To see how the values get encoding into the URL string, we can inspect the42resulting URL that was used to make the request:4344```python44```pycon45>>> r.url46URL('https://httpbin.org/get?key2=value2&key1=value1')47```4849You can also pass a list of items as a value:5051```python51```pycon52>>> params = {'key1': 'value1', 'key2': ['value2', 'value3']}53>>> r = httpx.get('https://httpbin.org/get', params=params)54>>> r.url55URL('https://httpbin.org/get?key1=value1&key2=value2&key2=value3')
2 unmodified lines
58## Response Content5960HTTPX will automatically handle decoding the response content into Unicode text.6162```python62```pycon63>>> r = httpx.get('https://www.example.org/')64>>> r.text65'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'66```6768You can inspect what encoding has been used to decode the response.6970```python70```pycon71>>> r.encoding72'UTF-8'73```7475If you need to override the standard behavior and explicitly set the encoding to76use, then you can do that too.7778```python78```pycon79>>> r.encoding = 'ISO-8859-1'80```8182## Binary Response Content8384The response content can also be accessed as bytes, for non-text responses:8586```python86```pycon87>>> r.content88b'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'89```90
2 unmodified lines
93encoding will also be supported.9495For example, to create an image from binary data returned by a request, you can use the following code:9697```python97```pycon98>>> from PIL import Image99>>> from io import BytesIO100>>> i = Image.open(BytesIO(r.content))101```
1 unmodified line
103## JSON Response Content104105Often Web API responses will be encoded as JSON.106107```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 line
113## Custom Headers114115To include additional headers in the outgoing request, use the `headers` keyword argument:116117```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 lines
125Some types of HTTP requests, such as `POST` and `PUT` requests, can include data126in the request body. One common way of including that is as form-encoded data,127which is used for HTML forms.128129```python129```pycon130>>> data = {'key1': 'value1', 'key2': 'value2'}131>>> r = httpx.post("https://httpbin.org/post", data=data)132>>> print(r.text)133{
7 unmodified lines
141```142143Form encoded data can also include multiple values from a given key.144145```python145```pycon146>>> data = {'key1': ['value1', 'value2']}147>>> r = httpx.post("https://httpbin.org/post", data=data)148>>> print(r.text)149{
11 unmodified lines
161## Sending Multipart File Uploads162163You can also upload files, using HTTP multipart encoding:164165```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 lines
177178You can also explicitly set the filename and content type, by using a tuple179of items for the file value:180181```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 lines
192```193194If you need to include non-file data fields in the multipart form, use the `data=...` parameter:195196```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 lines
214215Form encoded data is okay if all you need is a simple key-value data structure.216For more complicated data structures you'll often want to use JSON encoding instead.217218```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 lines
245## Response Status Codes246247We can inspect the HTTP status code of the response:248249```python249```pycon250>>> r = httpx.get('https://httpbin.org/get')251>>> r.status_code252200253```254255HTTPX also includes an easy shortcut for accessing status codes by their text phrase.256257```python257```pycon258>>> r.status_code == httpx.codes.OK259True260```261262We can raise an exception for any Client or Server error responses (4xx or 5xx status codes):263264```python264```pycon265>>> not_found = httpx.get('https://httpbin.org/status/404')266>>> not_found.status_code267404268>>> not_found.raise_for_status()
5 unmodified lines
274```275276Any successful response codes will simply return `None` rather than raising an exception.277278```python278```pycon279>>> r.raise_for_status()280```281282## Response Headers283284The response headers are available as a dictionary-like interface.285286```python286```pycon287>>> r.headers288Headers({289 'content-encoding': 'gzip',290 'transfer-encoding': 'chunked',
6 unmodified lines
297```298299The `Headers` data type is case-insensitive, so you can use any capitalization.300301```python301```pycon302>>> r.headers['Content-Type']303'application/json'304305>>> r.headers.get('content-type')
9 unmodified lines
315For large downloads you may want to use streaming responses that do not load the entire response body into memory at once.316317You can stream the binary content of the response...318319```python319```pycon320>>> with httpx.stream("GET", "https://www.example.com") as r:321... for data in r.iter_bytes():322... print(data)323```324325Or the text of the response...326327```python327```pycon328>>> with httpx.stream("GET", "https://www.example.com") as r:329... for text in r.iter_text():330... print(text)331```332333Or stream the text, on a line-by-line basis...334335```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 line
341HTTPX will use universal line endings, normalising all cases to `\n`.342343In 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.344345```python345```pycon346>>> with httpx.stream("GET", "https://www.example.com") as r:347... for chunk in r.iter_raw():348... print(chunk)349```350351If 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:352353```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 lines
360## Cookies361362Any cookies that are set on the response can be easily accessed:363364```python364```pycon365>>> r = httpx.get('http://httpbin.org/cookies/set?chocolate=chip', allow_redirects=False)366>>> r.cookies['chocolate']367'chip'368```369370To include cookies in an outgoing request, use the `cookies` parameter:371372```python372```pycon373>>> cookies = {"peanut": "butter"}374>>> r = httpx.get('http://httpbin.org/cookies', cookies=cookies)375>>> r.json()376{'cookies': {'peanut': 'butter'}}
1 unmodified line
378379Cookies are returned in a `Cookies` instance, which is a dict-like data structure380with additional API for accessing cookies by their domain or path.381382```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 lines
397in which they were made.398399For example, GitHub redirects all HTTP requests to HTTPS.400401```python401```pycon402>>> r = httpx.get('http://github.com/')403>>> r.url404URL('https://github.com/')405>>> r.status_code
3 unmodified lines
409```410411You can modify the default redirection handling with the allow_redirects parameter:412413```python413```pycon414>>> r = httpx.get('http://github.com/', allow_redirects=False)415>>> r.status_code416301417>>> r.history
1 unmodified line
419```420421If you’re making a `HEAD` request, you can use this to enable redirection:422423```python423```pycon424>>> r = httpx.head('http://github.com/', allow_redirects=True)425>>> r.url426'https://github.com/'427>>> r.history
8 unmodified lines
436437The default timeout for network inactivity is five seconds. You can modify the438value to be more or less strict:439440```python440```pycon441>>> httpx.get('https://github.com/', timeout=0.001)442```443444You can also disable the timeout behavior completely...445446```python446```pycon447>>> httpx.get('https://github.com/', timeout=None)448```449450For advanced timeout management, see [Timeout fine-tuning](advanced.md#fine-tuning-the-configuration).
5 unmodified lines
456To provide Basic authentication credentials, pass a 2-tuple of457plaintext `str` or `bytes` objects as the `auth` argument to the request458functions:459460```python460```pycon461>>> httpx.get("https://example.com", auth=("my_user", "password123"))462```463464To provide credentials for Digest authentication you'll need to instantiate465a `DigestAuth` object with the plaintext username and password as arguments.466This object can be then passed as the `auth` argument to the request methods467as above:468469```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 lines
22---2324Let's get started...2526```python26```pycon27>>> import httpx28>>> r = httpx.get('https://www.example.org/')29>>> r30<Response [200 OK]>
8 unmodified lines
39Or, using the async API...4041_Use [IPython](https://ipython.readthedocs.io/en/stable/) or Python 3.8+ with `python -m asyncio` to try this code interactively._4243```python43```pycon44>>> import httpx45>>> async with httpx.AsyncClient() as client:46>>> r = await client.get('https://www.example.org/')47>>> r
86 unmodified lines