1 from __future__ import annotations 2 3 import contextlib 4 import typing 5 6 from ._models import URL, Extensions, HeaderTypes, Response 7 from ._sync.connection_pool import ConnectionPool 8 9 10 def request( 11 method: bytes | str, 12 url: URL | bytes | str, 13 *, 14 headers: HeaderTypes = None, 15 content: bytes | typing.Iterator[bytes] | None = None, 16 extensions: Extensions | None = None, 17 ) -> Response: 18 """ 19 Sends an HTTP request, returning the response. 20 21 ``` 22 response = httpcore.request("GET", "https://www.example.com/") 23 ``` 24 25 Arguments: 26 method: The HTTP method for the request. Typically one of `"GET"`, 27 `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. 28 url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, 29 or as str/bytes. 30 headers: The HTTP request headers. Either as a dictionary of str/bytes, 31 or as a list of two-tuples of str/bytes. 32 content: The content of the request body. Either as bytes, 33 or as a bytes iterator. 34 extensions: A dictionary of optional extra information included on the request. 35 Possible keys include `"timeout"`. 36 37 Returns: 38 An instance of `httpcore.Response`. 39 """ 40 with ConnectionPool() as pool: 41 return pool.request( 42 method=method, 43 url=url, 44 headers=headers, 45 content=content, 46 extensions=extensions, 47 ) 48 49 50 @contextlib.contextmanager 51 def stream( 52 method: bytes | str, 53 url: URL | bytes | str, 54 *, 55 headers: HeaderTypes = None, 56 content: bytes | typing.Iterator[bytes] | None = None, 57 extensions: Extensions | None = None, 58 ) -> typing.Iterator[Response]: 59 """ 60 Sends an HTTP request, returning the response within a content manager. 61 62 ``` 63 with httpcore.stream("GET", "https://www.example.com/") as response: 64 ... 65 ``` 66 67 When using the `stream()` function, the body of the response will not be 68 automatically read. If you want to access the response body you should 69 either use `content = response.read()`, or `for chunk in response.iter_content()`. 70 71 Arguments: 72 method: The HTTP method for the request. Typically one of `"GET"`, 73 `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. 74 url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, 75 or as str/bytes. 76 headers: The HTTP request headers. Either as a dictionary of str/bytes, 77 or as a list of two-tuples of str/bytes. 78 content: The content of the request body. Either as bytes, 79 or as a bytes iterator. 80 extensions: A dictionary of optional extra information included on the request. 81 Possible keys include `"timeout"`. 82 83 Returns: 84 An instance of `httpcore.Response`. 85 """ 86 with ConnectionPool() as pool: 87 with pool.stream( 88 method=method, 89 url=url, 90 headers=headers, 91 content=content, 92 extensions=extensions, 93 ) as response: 94 yield response 95