Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/asttokens/__init__.pyAdded+24
- lib/python3.12/site-packages/asttokens/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/asttokens/__pycache__/astroid_compat.cpython-312.pycAdded
- lib/python3.12/site-packages/asttokens/__pycache__/asttokens.cpython-312.pycAdded
- lib/python3.12/site-packages/asttokens/__pycache__/line_numbers.cpython-312.pycAdded
- lib/python3.12/site-packages/asttokens/__pycache__/mark_tokens.cpython-312.pycAdded
- lib/python3.12/site-packages/asttokens/__pycache__/util.cpython-312.pycAdded
- lib/python3.12/site-packages/asttokens/__pycache__/version.cpython-312.pycAdded
- lib/python3.12/site-packages/asttokens/astroid_compat.pyAdded+18
- lib/python3.12/site-packages/asttokens/asttokens.pyAdded+450
- lib/python3.12/site-packages/asttokens/line_numbers.pyAdded+74
- lib/python3.12/site-packages/asttokens/mark_tokens.pyAdded+469
- lib/python3.12/site-packages/asttokens/py.typedAdded
- lib/python3.12/site-packages/asttokens/version.pyAdded+1
- lib/python3.12/site-packages/h11-0.16.0.dist-info/INSTALLERAdded+1
- lib/python3.12/site-packages/h11-0.16.0.dist-info/METADATAAdded+202
- lib/python3.12/site-packages/h11-0.16.0.dist-info/RECORDAdded+29
- lib/python3.12/site-packages/h11-0.16.0.dist-info/WHEELAdded+5
- lib/python3.12/site-packages/h11-0.16.0.dist-info/licenses/LICENSE.txtAdded+22
- lib/python3.12/site-packages/h11-0.16.0.dist-info/top_level.txtAdded+1
- lib/python3.12/site-packages/httpcore/__init__.pyAdded+141
- lib/python3.12/site-packages/httpcore/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/__pycache__/_api.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/__pycache__/_exceptions.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/__pycache__/_models.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/__pycache__/_ssl.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/__pycache__/_synchronization.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/__pycache__/_trace.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/__pycache__/_utils.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/_api.pyAdded+94
- lib/python3.12/site-packages/httpcore/_async/__init__.pyAdded+39
- lib/python3.12/site-packages/httpcore/_async/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/_async/__pycache__/connection.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/_async/__pycache__/connection_pool.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/_async/__pycache__/http11.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/_async/__pycache__/http2.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/_async/__pycache__/http_proxy.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/_async/__pycache__/interfaces.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/_async/__pycache__/socks_proxy.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/_async/connection.pyAdded+222
- lib/python3.12/site-packages/httpcore/_async/connection_pool.pyAdded+420
- lib/python3.12/site-packages/httpcore/_async/http11.pyAdded+379
- lib/python3.12/site-packages/httpcore/_async/http2.pyAdded+592
- lib/python3.12/site-packages/httpcore/_async/http_proxy.pyAdded+367
- lib/python3.12/site-packages/httpcore/_async/interfaces.pyAdded+137
- lib/python3.12/site-packages/httpcore/_async/socks_proxy.pyAdded+341
- lib/python3.12/site-packages/httpcore/_backends/__init__.pyAdded
- lib/python3.12/site-packages/httpcore/_backends/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/_backends/__pycache__/anyio.cpython-312.pycAdded
- lib/python3.12/site-packages/httpcore/_backends/__pycache__/auto.cpython-312.pycAdded
123456789101112131415161718192021222324# Copyright 2016 Grist Labs, Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
"""This module enhances the Python AST tree with token and source code information, sufficent todetect the source text of each AST node. This is helpful for tools that make source codetransformations."""
from .line_numbers import LineNumbersfrom .asttokens import ASTText, ASTTokens, supports_tokenless
__all__ = ['ASTText', 'ASTTokens', 'LineNumbers', 'supports_tokenless']123456789101112131415161718try: from astroid import nodes as astroid_node_classes
# astroid_node_classes should be whichever module has the NodeNG class from astroid.nodes import NodeNG from astroid.nodes import BaseContainerexcept Exception: try: from astroid import node_classes as astroid_node_classes from astroid.node_classes import NodeNG from astroid.node_classes import _BaseContainer as BaseContainer except Exception: # pragma: no cover astroid_node_classes = None NodeNG = None BaseContainer = None
__all__ = ["astroid_node_classes", "NodeNG", "BaseContainer"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450# Copyright 2016 Grist Labs, Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import abcimport astimport bisectimport sysimport tokenfrom ast import Modulefrom typing import Iterable, Iterator, List, Optional, Tuple, Any, cast, TYPE_CHECKING
from .line_numbers import LineNumbersfrom .util import ( Token, match_token, is_non_coding_token, patched_generate_tokens, last_stmt, annotate_fstring_nodes, generate_tokens, is_module, is_stmt)
if TYPE_CHECKING: # pragma: no cover from .util import AstNode, TokenInfo
class ASTTextBase(metaclass=abc.ABCMeta): def __init__(self, source_text: str, filename: str) -> None: self._filename = filename
# Decode source after parsing to let Python 2 handle coding declarations. # (If the encoding was not utf-8 compatible, then even if it parses correctly, # we'll fail with a unicode error here.) source_text = str(source_text)
self._text = source_text self._line_numbers = LineNumbers(source_text)
@abc.abstractmethod def get_text_positions(self, node, padded): # type: (AstNode, bool) -> Tuple[Tuple[int, int], Tuple[int, int]] """ Returns two ``(lineno, col_offset)`` tuples for the start and end of the given node. If the positions can't be determined, or the nodes don't correspond to any particular text, returns ``(1, 0)`` for both.
``padded`` corresponds to the ``padded`` argument to ``ast.get_source_segment()``. This means that if ``padded`` is True, the start position will be adjusted to include leading whitespace if ``node`` is a multiline statement. """ raise NotImplementedError # pragma: no cover
def get_text_range(self, node, padded=True): # type: (AstNode, bool) -> Tuple[int, int] """ Returns the (startpos, endpos) positions in source text corresponding to the given node. Returns (0, 0) for nodes (like `Load`) that don't correspond to any particular text.
See ``get_text_positions()`` for details on the ``padded`` argument. """ start, end = self.get_text_positions(node, padded) return ( self._line_numbers.line_to_offset(*start), self._line_numbers.line_to_offset(*end), )
def get_text(self, node, padded=True): # type: (AstNode, bool) -> str """ Returns the text corresponding to the given node. Returns '' for nodes (like `Load`) that don't correspond to any particular text.
See ``get_text_positions()`` for details on the ``padded`` argument. """ start, end = self.get_text_range(node, padded) return self._text[start: end]
class ASTTokens(ASTTextBase): """ ASTTokens maintains the text of Python code in several forms: as a string, as line numbers, and as tokens, and is used to mark and access token and position information.
``source_text`` must be a unicode or UTF8-encoded string. If you pass in UTF8 bytes, remember that all offsets you'll get are to the unicode text, which is available as the ``.text`` property.
If ``parse`` is set, the ``source_text`` will be parsed with ``ast.parse()``, and the resulting tree marked with token info and made available as the ``.tree`` property.
If ``tree`` is given, it will be marked and made available as the ``.tree`` property. In addition to the trees produced by the ``ast`` module, ASTTokens will also mark trees produced using ``astroid`` library <https://www.astroid.org>.
If only ``source_text`` is given, you may use ``.mark_tokens(tree)`` to mark the nodes of an AST tree created separately. """
def __init__(self, source_text, parse=False, tree=None, filename='<unknown>', tokens=None): # type: (Any, bool, Optional[Module], str, Optional[Iterable[TokenInfo]]) -> None super(ASTTokens, self).__init__(source_text, filename)
self._tree = ast.parse(source_text, filename) if parse else tree
# Tokenize the code. if tokens is None: tokens = generate_tokens(self._text) self._tokens = list(self._translate_tokens(tokens))
# Extract the start positions of all tokens, so that we can quickly map positions to tokens. self._token_offsets = [tok.startpos for tok in self._tokens]
if self._tree: self.mark_tokens(self._tree)
def mark_tokens(self, root_node): # type: (Module) -> None """ Given the root of the AST or Astroid tree produced from source_text, visits all nodes marking them with token and position information by adding ``.first_token`` and ``.last_token`` attributes. This is done automatically in the constructor when ``parse`` or ``tree`` arguments are set, but may be used manually with a separate AST or Astroid tree. """ # The hard work of this class is done by MarkTokens from .mark_tokens import MarkTokens # to avoid import loops MarkTokens(self).visit_tree(root_node)
def _translate_tokens(self, original_tokens): # type: (Iterable[TokenInfo]) -> Iterator[Token] """ Translates the given standard library tokens into our own representation. """ for index, tok in enumerate(patched_generate_tokens(original_tokens)): tok_type, tok_str, start, end, line = tok yield Token(tok_type, tok_str, start, end, line, index, self._line_numbers.line_to_offset(start[0], start[1]), self._line_numbers.line_to_offset(end[0], end[1]))
@property def text(self): # type: () -> str """The source code passed into the constructor.""" return self._text
@property def tokens(self): # type: () -> List[Token] """The list of tokens corresponding to the source code from the constructor.""" return self._tokens
@property def tree(self): # type: () -> Optional[Module] """The root of the AST tree passed into the constructor or parsed from the source code.""" return self._tree
@property def filename(self): # type: () -> str """The filename that was parsed""" return self._filename
def get_token_from_offset(self, offset): # type: (int) -> Token """ Returns the token containing the given character offset (0-based position in source text), or the preceeding token if the position is between tokens. """ return self._tokens[bisect.bisect(self._token_offsets, offset) - 1]
def get_token(self, lineno, col_offset): # type: (int, int) -> Token """ Returns the token containing the given (lineno, col_offset) position, or the preceeding token if the position is between tokens. """ # TODO: add test for multibyte unicode. We need to translate offsets from ast module (which # are in utf8) to offsets into the unicode text. tokenize module seems to use unicode offsets # but isn't explicit. return self.get_token_from_offset(self._line_numbers.line_to_offset(lineno, col_offset))
def get_token_from_utf8(self, lineno, col_offset): # type: (int, int) -> Token """ Same as get_token(), but interprets col_offset as a UTF8 offset, which is what `ast` uses. """ return self.get_token(lineno, self._line_numbers.from_utf8_col(lineno, col_offset))
def next_token(self, tok, include_extra=False): # type: (Token, bool) -> Token """ Returns the next token after the given one. If include_extra is True, includes non-coding tokens from the tokenize module, such as NL and COMMENT. """ i = tok.index + 1 if not include_extra: while is_non_coding_token(self._tokens[i].type): i += 1 return self._tokens[i]
def prev_token(self, tok, include_extra=False): # type: (Token, bool) -> Token """ Returns the previous token before the given one. If include_extra is True, includes non-coding tokens from the tokenize module, such as NL and COMMENT. """ i = tok.index - 1 if not include_extra: while is_non_coding_token(self._tokens[i].type): i -= 1 return self._tokens[i]
def find_token(self, start_token, tok_type, tok_str=None, reverse=False): # type: (Token, int, Optional[str], bool) -> Token """ Looks for the first token, starting at start_token, that matches tok_type and, if given, the token string. Searches backwards if reverse is True. Returns ENDMARKER token if not found (you can check it with `token.ISEOF(t.type)`). """ t = start_token advance = self.prev_token if reverse else self.next_token while not match_token(t, tok_type, tok_str) and not token.ISEOF(t.type): t = advance(t, include_extra=True) return t
def token_range(self, first_token, # type: Token last_token, # type: Token include_extra=False, # type: bool ): # type: (...) -> Iterator[Token] """ Yields all tokens in order from first_token through and including last_token. If include_extra is True, includes non-coding tokens such as tokenize.NL and .COMMENT. """ for i in range(first_token.index, last_token.index + 1): if include_extra or not is_non_coding_token(self._tokens[i].type): yield self._tokens[i]
def get_tokens(self, node, include_extra=False): # type: (AstNode, bool) -> Iterator[Token] """ Yields all tokens making up the given node. If include_extra is True, includes non-coding tokens such as tokenize.NL and .COMMENT. """ return self.token_range(node.first_token, node.last_token, include_extra=include_extra)
def get_text_positions(self, node, padded): # type: (AstNode, bool) -> Tuple[Tuple[int, int], Tuple[int, int]] """ Returns two ``(lineno, col_offset)`` tuples for the start and end of the given node. If the positions can't be determined, or the nodes don't correspond to any particular text, returns ``(1, 0)`` for both.
``padded`` corresponds to the ``padded`` argument to ``ast.get_source_segment()``. This means that if ``padded`` is True, the start position will be adjusted to include leading whitespace if ``node`` is a multiline statement. """ if not hasattr(node, 'first_token'): return (1, 0), (1, 0)
start = node.first_token.start end = node.last_token.end if padded and any(match_token(t, token.NEWLINE) for t in self.get_tokens(node)): # Set col_offset to 0 to include leading indentation for multiline statements. start = (start[0], 0)
return start, end
class ASTText(ASTTextBase): """ Supports the same ``get_text*`` methods as ``ASTTokens``, but uses the AST to determine the text positions instead of tokens. This is faster than ``ASTTokens`` as it requires less setup work.
It also (sometimes) supports nodes inside f-strings, which ``ASTTokens`` doesn't.
Some node types and/or Python versions are not supported. In these cases the ``get_text*`` methods will fall back to using ``ASTTokens`` which incurs the usual setup cost the first time. If you want to avoid this, check ``supports_tokenless(node)`` before calling ``get_text*`` methods. """ def __init__(self, source_text, tree=None, filename='<unknown>'): # type: (Any, Optional[Module], str) -> None super(ASTText, self).__init__(source_text, filename)
self._tree = tree if self._tree is not None: annotate_fstring_nodes(self._tree)
self._asttokens = None # type: Optional[ASTTokens]
@property def tree(self): # type: () -> Module if self._tree is None: self._tree = ast.parse(self._text, self._filename) annotate_fstring_nodes(self._tree) return self._tree
@property def asttokens(self): # type: () -> ASTTokens if self._asttokens is None: self._asttokens = ASTTokens( self._text, tree=self.tree, filename=self._filename, ) return self._asttokens
def _get_text_positions_tokenless(self, node, padded): # type: (AstNode, bool) -> Tuple[Tuple[int, int], Tuple[int, int]] """ Version of ``get_text_positions()`` that doesn't use tokens. """ if is_module(node): # Modules don't have position info, so just return the range of the whole text. # The token-using method does something different, but its behavior seems weird and inconsistent. # For example, in a file with only comments, it only returns the first line. # It's hard to imagine a case when this matters. return (1, 0), self._line_numbers.offset_to_line(len(self._text))
if getattr(node, 'lineno', None) is None: return (1, 0), (1, 0)
assert node # tell mypy that node is not None, which we allowed up to here for compatibility
decorators = getattr(node, 'decorator_list', []) if not decorators: # Astroid uses node.decorators.nodes instead of node.decorator_list. decorators_node = getattr(node, 'decorators', None) decorators = getattr(decorators_node, 'nodes', []) if decorators: # Function/Class definition nodes are marked by AST as starting at def/class, # not the first decorator. This doesn't match the token-using behavior, # or inspect.getsource(), and just seems weird. start_node = decorators[0] else: start_node = node
start_lineno = start_node.lineno end_node = last_stmt(node)
# Include leading indentation for multiline statements. # This doesn't mean simple statements that happen to be on multiple lines, # but compound statements where inner indentation matters. # So we don't just compare node.lineno and node.end_lineno, # we check for a contained statement starting on a different line. if padded and ( start_lineno != end_node.lineno or ( # Astroid docstrings aren't treated as separate statements. # So to handle function/class definitions with a docstring but no other body, # we just check that the node is a statement with a docstring # and spanning multiple lines in the simple, literal sense. start_lineno != node.end_lineno and getattr(node, "doc_node", None) and is_stmt(node) ) ): start_col_offset = 0 else: start_col_offset = self._line_numbers.from_utf8_col(start_lineno, start_node.col_offset)
start = (start_lineno, start_col_offset)
# To match the token-using behaviour, we exclude trailing semicolons and comments. # This means that for blocks containing multiple statements, we have to use the last one # instead of the actual node for end_lineno and end_col_offset. end_lineno = cast(int, end_node.end_lineno) end_col_offset = cast(int, end_node.end_col_offset) end_col_offset = self._line_numbers.from_utf8_col(end_lineno, end_col_offset) end = (end_lineno, end_col_offset)
return start, end
def get_text_positions(self, node, padded): # type: (AstNode, bool) -> Tuple[Tuple[int, int], Tuple[int, int]] """ Returns two ``(lineno, col_offset)`` tuples for the start and end of the given node. If the positions can't be determined, or the nodes don't correspond to any particular text, returns ``(1, 0)`` for both.
``padded`` corresponds to the ``padded`` argument to ``ast.get_source_segment()``. This means that if ``padded`` is True, the start position will be adjusted to include leading whitespace if ``node`` is a multiline statement. """ if getattr(node, "_broken_positions", None): # This node was marked in util.annotate_fstring_nodes as having untrustworthy lineno/col_offset. return (1, 0), (1, 0)
if supports_tokenless(node): return self._get_text_positions_tokenless(node, padded)
return self.asttokens.get_text_positions(node, padded)
# Node types that _get_text_positions_tokenless doesn't support.# These initial values are missing lineno._unsupported_tokenless_types = ("arguments", "Arguments", "withitem") # type: Tuple[str, ...]if sys.version_info[:2] == (3, 8): # _get_text_positions_tokenless works incorrectly for these types due to bugs in Python 3.8. _unsupported_tokenless_types += ("arg", "Starred") # no lineno in 3.8 _unsupported_tokenless_types += ("Slice", "ExtSlice", "Index", "keyword")
def supports_tokenless(node=None): # type: (Any) -> bool """ Returns True if the Python version and the node (if given) are supported by the ``get_text*`` methods of ``ASTText`` without falling back to ``ASTTokens``. See ``ASTText`` for why this matters.
The following cases are not supported:
- PyPy - ``ast.arguments`` / ``astroid.Arguments`` - ``ast.withitem`` - ``astroid.Comprehension`` - ``astroid.AssignName`` inside ``astroid.Arguments`` or ``astroid.ExceptHandler`` - The following nodes in Python 3.8 only: - ``ast.arg`` - ``ast.Starred`` - ``ast.Slice`` - ``ast.ExtSlice`` - ``ast.Index`` - ``ast.keyword`` """ return ( type(node).__name__ not in _unsupported_tokenless_types and not ( # astroid nodes not isinstance(node, ast.AST) and node is not None and ( ( type(node).__name__ == "AssignName" and type(node.parent).__name__ in ("Arguments", "ExceptHandler") ) ) ) and 'pypy' not in sys.version.lower() )1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374# Copyright 2016 Grist Labs, Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import bisectimport refrom typing import Dict, List, Tuple
_line_start_re = re.compile(r'^', re.M)
class LineNumbers: """ Class to convert between character offsets in a text string, and pairs (line, column) of 1-based line and 0-based column numbers, as used by tokens and AST nodes.
This class expects unicode for input and stores positions in unicode. But it supports translating to and from utf8 offsets, which are used by ast parsing. """ def __init__(self, text): # type: (str) -> None # A list of character offsets of each line's first character. self._line_offsets = [m.start(0) for m in _line_start_re.finditer(text)] self._text = text self._text_len = len(text) self._utf8_offset_cache = {} # type: Dict[int, List[int]] # maps line num to list of char offset for each byte in line
def from_utf8_col(self, line, utf8_column): # type: (int, int) -> int """ Given a 1-based line number and 0-based utf8 column, returns a 0-based unicode column. """ offsets = self._utf8_offset_cache.get(line) if offsets is None: end_offset = self._line_offsets[line] if line < len(self._line_offsets) else self._text_len line_text = self._text[self._line_offsets[line - 1] : end_offset]
offsets = [i for i,c in enumerate(line_text) for byte in c.encode('utf8')] offsets.append(len(line_text)) self._utf8_offset_cache[line] = offsets
return offsets[max(0, min(len(offsets)-1, utf8_column))]
def line_to_offset(self, line, column): # type: (int, int) -> int """ Converts 1-based line number and 0-based column to 0-based character offset into text. """ line -= 1 if line >= len(self._line_offsets): return self._text_len elif line < 0: return 0 else: return min(self._line_offsets[line] + max(0, column), self._text_len)
def offset_to_line(self, offset): # type: (int) -> Tuple[int, int] """ Converts 0-based character offset to pair (line, col) of 1-based line and 0-based column numbers. """ offset = max(0, min(self._text_len, offset)) line_index = bisect.bisect_right(self._line_offsets, offset) - 1 return (line_index + 1, offset - self._line_offsets[line_index])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469# Copyright 2016 Grist Labs, Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import astimport numbersimport sysimport tokenfrom ast import Modulefrom typing import Callable, List, Union, cast, Optional, Tuple, TYPE_CHECKING
from . import utilfrom .asttokens import ASTTokensfrom .astroid_compat import astroid_node_classes as nc, BaseContainer as AstroidBaseContainer
if TYPE_CHECKING: from .util import AstNode
# Mapping of matching braces. To find a token here, look up token[:2]._matching_pairs_left = { (token.OP, '('): (token.OP, ')'), (token.OP, '['): (token.OP, ']'), (token.OP, '{'): (token.OP, '}'),}
_matching_pairs_right = { (token.OP, ')'): (token.OP, '('), (token.OP, ']'): (token.OP, '['), (token.OP, '}'): (token.OP, '{'),}
class MarkTokens: """ Helper that visits all nodes in the AST tree and assigns .first_token and .last_token attributes to each of them. This is the heart of the token-marking logic. """ def __init__(self, code): # type: (ASTTokens) -> None self._code = code self._methods = util.NodeMethods() self._iter_children = None # type: Optional[Callable]
def visit_tree(self, node): # type: (Module) -> None self._iter_children = util.iter_children_func(node) util.visit_tree(node, self._visit_before_children, self._visit_after_children)
def _visit_before_children(self, node, parent_token): # type: (AstNode, Optional[util.Token]) -> Tuple[Optional[util.Token], Optional[util.Token]] col = getattr(node, 'col_offset', None) token = self._code.get_token_from_utf8(node.lineno, col) if col is not None else None
if not token and util.is_module(node): # We'll assume that a Module node starts at the start of the source code. token = self._code.get_token(1, 0)
# Use our own token, or our parent's if we don't have one, to pass to child calls as # parent_token argument. The second value becomes the token argument of _visit_after_children. return (token or parent_token, token)
def _visit_after_children(self, node, parent_token, token): # type: (AstNode, Optional[util.Token], Optional[util.Token]) -> None # This processes the node generically first, after all children have been processed.
# Get the first and last tokens that belong to children. Note how this doesn't assume that we # iterate through children in order that corresponds to occurrence in source code. This # assumption can fail (e.g. with return annotations). first = token last = None for child in cast(Callable, self._iter_children)(node): # astroid slices have especially wrong positions, we don't want them to corrupt their parents. if util.is_empty_astroid_slice(child): continue if not first or child.first_token.index < first.index: first = child.first_token if not last or child.last_token.index > last.index: last = child.last_token
# If we don't have a first token from _visit_before_children, and there were no children, then # use the parent's token as the first token. first = first or parent_token
# If no children, set last token to the first one. last = last or first
# Statements continue to before NEWLINE. This helps cover a few different cases at once. if util.is_stmt(node): last = self._find_last_in_stmt(cast(util.Token, last))
# Capture any unmatched brackets. first, last = self._expand_to_matching_pairs(cast(util.Token, first), cast(util.Token, last), node)
# Give a chance to node-specific methods to adjust. nfirst, nlast = self._methods.get(self, node.__class__)(node, first, last)
if (nfirst, nlast) != (first, last): # If anything changed, expand again to capture any unmatched brackets. nfirst, nlast = self._expand_to_matching_pairs(nfirst, nlast, node)
node.first_token = nfirst node.last_token = nlast
def _find_last_in_stmt(self, start_token): # type: (util.Token) -> util.Token t = start_token while (not util.match_token(t, token.NEWLINE) and not util.match_token(t, token.OP, ';') and not token.ISEOF(t.type)): t = self._code.next_token(t, include_extra=True) return self._code.prev_token(t)
def _expand_to_matching_pairs(self, first_token, last_token, node): # type: (util.Token, util.Token, AstNode) -> Tuple[util.Token, util.Token] """ Scan tokens in [first_token, last_token] range that are between node's children, and for any unmatched brackets, adjust first/last tokens to include the closing pair. """ # We look for opening parens/braces among non-child tokens (i.e. tokens between our actual # child nodes). If we find any closing ones, we match them to the opens. to_match_right = [] # type: List[Tuple[int, str]] to_match_left = [] for tok in self._code.token_range(first_token, last_token): tok_info = tok[:2] if to_match_right and tok_info == to_match_right[-1]: to_match_right.pop() elif tok_info in _matching_pairs_left: to_match_right.append(_matching_pairs_left[tok_info]) elif tok_info in _matching_pairs_right: to_match_left.append(_matching_pairs_right[tok_info])
# Once done, extend `last_token` to match any unclosed parens/braces. for match in reversed(to_match_right): last = self._code.next_token(last_token) # Allow for trailing commas or colons (allowed in subscripts) before the closing delimiter while any(util.match_token(last, token.OP, x) for x in (',', ':')): last = self._code.next_token(last) # Now check for the actual closing delimiter. if util.match_token(last, *match): last_token = last
# And extend `first_token` to match any unclosed opening parens/braces. for match in to_match_left: first = self._code.prev_token(first_token) if util.match_token(first, *match): first_token = first
return (first_token, last_token)
#---------------------------------------------------------------------- # Node visitors. Each takes a preliminary first and last tokens, and returns the adjusted pair # that will actually be assigned.
def visit_default(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] # pylint: disable=no-self-use # By default, we don't need to adjust the token we computed earlier. return (first_token, last_token)
def handle_comp(self, open_brace, node, first_token, last_token): # type: (str, AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] # For list/set/dict comprehensions, we only get the token of the first child, so adjust it to # include the opening brace (the closing brace will be matched automatically). before = self._code.prev_token(first_token) util.expect_token(before, token.OP, open_brace) return (before, last_token)
def visit_comprehension(self, node, # type: AstNode first_token, # type: util.Token last_token, # type: util.Token ): # type: (...) -> Tuple[util.Token, util.Token] # The 'comprehension' node starts with 'for' but we only get first child; we search backwards # to find the 'for' keyword. first = self._code.find_token(first_token, token.NAME, 'for', reverse=True) return (first, last_token)
def visit_if(self, node, first_token, last_token): # type: (util.Token, util.Token, util.Token) -> Tuple[util.Token, util.Token] while first_token.string not in ('if', 'elif'): first_token = self._code.prev_token(first_token) return first_token, last_token
def handle_attr(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] # Attribute node has ".attr" (2 tokens) after the last child. dot = self._code.find_token(last_token, token.OP, '.') name = self._code.next_token(dot) util.expect_token(name, token.NAME) return (first_token, name)
visit_attribute = handle_attr visit_assignattr = handle_attr visit_delattr = handle_attr
def handle_def(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] # With astroid, nodes that start with a doc-string can have an empty body, in which case we # need to adjust the last token to include the doc string. if not node.body and (getattr(node, 'doc_node', None) or getattr(node, 'doc', None)): # type: ignore[union-attr] last_token = self._code.find_token(last_token, token.STRING)
# Include @ from decorator if first_token.index > 0: prev = self._code.prev_token(first_token) if util.match_token(prev, token.OP, '@'): first_token = prev return (first_token, last_token)
visit_classdef = handle_def visit_functiondef = handle_def
def handle_following_brackets(self, node, last_token, opening_bracket): # type: (AstNode, util.Token, str) -> util.Token # This is for calls and subscripts, which have a pair of brackets # at the end which may contain no nodes, e.g. foo() or bar[:]. # We look for the opening bracket and then let the matching pair be found automatically # Remember that last_token is at the end of all children, # so we are not worried about encountering a bracket that belongs to a child. first_child = next(cast(Callable, self._iter_children)(node)) call_start = self._code.find_token(first_child.last_token, token.OP, opening_bracket) if call_start.index > last_token.index: last_token = call_start return last_token
def visit_call(self, node, first_token, last_token): # type: (util.Token, util.Token, util.Token) -> Tuple[util.Token, util.Token] last_token = self.handle_following_brackets(node, last_token, '(')
# Handling a python bug with decorators with empty parens, e.g. # @deco() # def ... if util.match_token(first_token, token.OP, '@'): first_token = self._code.next_token(first_token) return (first_token, last_token)
def visit_matchclass(self, node, first_token, last_token): # type: (util.Token, util.Token, util.Token) -> Tuple[util.Token, util.Token] last_token = self.handle_following_brackets(node, last_token, '(') return (first_token, last_token)
def visit_subscript(self, node, # type: AstNode first_token, # type: util.Token last_token, # type: util.Token ): # type: (...) -> Tuple[util.Token, util.Token] last_token = self.handle_following_brackets(node, last_token, '[') return (first_token, last_token)
def visit_slice(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] # consume `:` tokens to the left and right. In Python 3.9, Slice nodes are # given a col_offset, (and end_col_offset), so this will always start inside # the slice, even if it is the empty slice. However, in 3.8 and below, this # will only expand to the full slice if the slice contains a node with a # col_offset. So x[:] will only get the correct tokens in 3.9, but x[1:] and # x[:1] will even on earlier versions of Python. while True: prev = self._code.prev_token(first_token) if prev.string != ':': break first_token = prev while True: next_ = self._code.next_token(last_token) if next_.string != ':': break last_token = next_ return (first_token, last_token)
def handle_bare_tuple(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] # A bare tuple doesn't include parens; if there is a trailing comma, make it part of the tuple. maybe_comma = self._code.next_token(last_token) if util.match_token(maybe_comma, token.OP, ','): last_token = maybe_comma return (first_token, last_token)
# In Python3.8 parsed tuples include parentheses when present. def handle_tuple_nonempty(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] assert isinstance(node, ast.Tuple) or isinstance(node, AstroidBaseContainer) # It's a bare tuple if the first token belongs to the first child. The first child may # include extraneous parentheses (which don't create new nodes), so account for those too. child = node.elts[0] if TYPE_CHECKING: child = cast(AstNode, child) child_first, child_last = self._gobble_parens(child.first_token, child.last_token, True) if first_token == child_first: return self.handle_bare_tuple(node, first_token, last_token) return (first_token, last_token)
def visit_tuple(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] assert isinstance(node, ast.Tuple) or isinstance(node, AstroidBaseContainer) if not node.elts: # An empty tuple is just "()", and we need no further info. return (first_token, last_token) return self.handle_tuple_nonempty(node, first_token, last_token)
def _gobble_parens(self, first_token, last_token, include_all=False): # type: (util.Token, util.Token, bool) -> Tuple[util.Token, util.Token] # Expands a range of tokens to include one or all pairs of surrounding parentheses, and # returns (first, last) tokens that include these parens. while first_token.index > 0: prev = self._code.prev_token(first_token) next = self._code.next_token(last_token) if util.match_token(prev, token.OP, '(') and util.match_token(next, token.OP, ')'): first_token, last_token = prev, next if include_all: continue break return (first_token, last_token)
def visit_str(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] return self.handle_str(first_token, last_token)
def visit_joinedstr(self, node, # type: AstNode first_token, # type: util.Token last_token, # type: util.Token ): # type: (...) -> Tuple[util.Token, util.Token] if sys.version_info < (3, 12): # Older versions don't tokenize the contents of f-strings return self.handle_str(first_token, last_token)
last = first_token while True: if util.match_token(last, getattr(token, "FSTRING_START")): # Python 3.12+ has tokens for the start (e.g. `f"`) and end (`"`) # of the f-string. We can't just look for the next FSTRING_END # because f-strings can be nested, e.g. f"{f'{x}'}", so we need # to treat this like matching balanced parentheses. count = 1 while count > 0: last = self._code.next_token(last) # mypy complains about token.FSTRING_START and token.FSTRING_END. if util.match_token(last, getattr(token, "FSTRING_START")): count += 1 elif util.match_token(last, getattr(token, "FSTRING_END")): count -= 1 last_token = last last = self._code.next_token(last_token) elif util.match_token(last, token.STRING): # Similar to handle_str, we also need to handle adjacent strings. last_token = last last = self._code.next_token(last_token) else: break return (first_token, last_token)
def visit_bytes(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] return self.handle_str(first_token, last_token)
def handle_str(self, first_token, last_token): # type: (util.Token, util.Token) -> Tuple[util.Token, util.Token] # Multiple adjacent STRING tokens form a single string. last = self._code.next_token(last_token) while util.match_token(last, token.STRING): last_token = last last = self._code.next_token(last_token) return (first_token, last_token)
def handle_num(self, node, # type: AstNode value, # type: Union[complex, int, numbers.Number] first_token, # type: util.Token last_token, # type: util.Token ): # type: (...) -> Tuple[util.Token, util.Token] # A constant like '-1' gets turned into two tokens; this will skip the '-'. while util.match_token(last_token, token.OP): last_token = self._code.next_token(last_token)
if isinstance(value, complex): # A complex number like -2j cannot be compared directly to 0 # A complex number like 1-2j is expressed as a binary operation # so we don't need to worry about it value = value.imag
# This makes sure that the - is included if value < 0 and first_token.type == token.NUMBER: # type: ignore[operator] first_token = self._code.prev_token(first_token) return (first_token, last_token)
def visit_num(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] n = node.n # type: ignore[union-attr] # ast.Num has been removed in python 3.14 assert isinstance(n, (complex, int, numbers.Number)) return self.handle_num(node, n, first_token, last_token)
def visit_const(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] assert isinstance(node, ast.Constant) or isinstance(node, nc.Const) if isinstance(node.value, numbers.Number): return self.handle_num(node, node.value, first_token, last_token) elif isinstance(node.value, (str, bytes)): return self.visit_str(node, first_token, last_token) return (first_token, last_token)
visit_constant = visit_const
def visit_keyword(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] # Until python 3.9 (https://bugs.python.org/issue40141), # ast.keyword nodes didn't have line info. Astroid has lineno None. assert isinstance(node, ast.keyword) or isinstance(node, nc.Keyword) if node.arg is not None and getattr(node, 'lineno', None) is None: equals = self._code.find_token(first_token, token.OP, '=', reverse=True) name = self._code.prev_token(equals) util.expect_token(name, token.NAME, node.arg) first_token = name return (first_token, last_token)
def visit_starred(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] # Astroid has 'Starred' nodes (for "foo(*bar)" type args), but they need to be adjusted. if not util.match_token(first_token, token.OP, '*'): star = self._code.prev_token(first_token) if util.match_token(star, token.OP, '*'): first_token = star return (first_token, last_token)
def visit_assignname(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] # Astroid may turn 'except' clause into AssignName, but we need to adjust it. if util.match_token(first_token, token.NAME, 'except'): colon = self._code.find_token(last_token, token.OP, ':') first_token = last_token = self._code.prev_token(colon) return (first_token, last_token)
# Async nodes should typically start with the word 'async' # but Python < 3.7 doesn't put the col_offset there # AsyncFunctionDef is slightly different because it might have # decorators before that, which visit_functiondef handles def handle_async(self, node, first_token, last_token): # type: (AstNode, util.Token, util.Token) -> Tuple[util.Token, util.Token] if not first_token.string == 'async': first_token = self._code.prev_token(first_token) return (first_token, last_token)
visit_asyncfor = handle_async visit_asyncwith = handle_async
def visit_asyncfunctiondef(self, node, # type: AstNode first_token, # type: util.Token last_token, # type: util.Token ): # type: (...) -> Tuple[util.Token, util.Token] if util.match_token(first_token, token.NAME, 'def'): # Include the 'async' token first_token = self._code.prev_token(first_token) return self.visit_functiondef(node, first_token, last_token)1__version__ = "3.0.1"1pip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202Metadata-Version: 2.4Name: h11Version: 0.16.0Summary: A pure-Python, bring-your-own-I/O implementation of HTTP/1.1Home-page: https://github.com/python-hyper/h11Author: Nathaniel J. SmithAuthor-email: njs@pobox.comLicense: MITClassifier: Development Status :: 3 - AlphaClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: MIT LicenseClassifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Topic :: Internet :: WWW/HTTPClassifier: Topic :: System :: NetworkingRequires-Python: >=3.8License-File: LICENSE.txtDynamic: authorDynamic: author-emailDynamic: classifierDynamic: descriptionDynamic: home-pageDynamic: licenseDynamic: license-fileDynamic: requires-pythonDynamic: summary
h11===
.. image:: https://travis-ci.org/python-hyper/h11.svg?branch=master :target: https://travis-ci.org/python-hyper/h11 :alt: Automated test status
.. image:: https://codecov.io/gh/python-hyper/h11/branch/master/graph/badge.svg :target: https://codecov.io/gh/python-hyper/h11 :alt: Test coverage
.. image:: https://readthedocs.org/projects/h11/badge/?version=latest :target: http://h11.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status
This is a little HTTP/1.1 library written from scratch in Python,heavily inspired by `hyper-h2 <https://hyper-h2.readthedocs.io/>`_.
It's a "bring-your-own-I/O" library; h11 contains no IO codewhatsoever. This means you can hook h11 up to your favorite networkAPI, and that could be anything you want: synchronous, threaded,asynchronous, or your own implementation of `RFC 6214<https://tools.ietf.org/html/rfc6214>`_ -- h11 won't judge you.(Compare this to the current state of the art, where every time a `newnetwork API <https://trio.readthedocs.io/>`_ comes along then someonegets to start over reimplementing the entire HTTP protocol fromscratch.) Cory Benfield made an `excellent blog post describing thebenefits of this approach<https://lukasa.co.uk/2015/10/The_New_Hyper/>`_, or if you like videothen here's his `PyCon 2016 talk on the same theme<https://www.youtube.com/watch?v=7cC3_jGwl_U>`_.
This also means that h11 is not immediately useful out of the box:it's a toolkit for building programs that speak HTTP, not somethingthat could directly replace ``requests`` or ``twisted.web`` orwhatever. But h11 makes it much easier to implement something like``requests`` or ``twisted.web``.
At a high level, working with h11 goes like this:
1) First, create an ``h11.Connection`` object to track the state of a single HTTP/1.1 connection.
2) When you read data off the network, pass it to ``conn.receive_data(...)``; you'll get back a list of objects representing high-level HTTP "events".
3) When you want to send a high-level HTTP event, create the corresponding "event" object and pass it to ``conn.send(...)``; this will give you back some bytes that you can then push out through the network.
For example, a client might instantiate and then send a``h11.Request`` object, then zero or more ``h11.Data`` objects for therequest body (e.g., if this is a POST), and then a``h11.EndOfMessage`` to indicate the end of the message. Then theserver would then send back a ``h11.Response``, some ``h11.Data``, andits own ``h11.EndOfMessage``. If either side violates the protocol,you'll get a ``h11.ProtocolError`` exception.
h11 is suitable for implementing both servers and clients, and has apleasantly symmetric API: the events you send as a client are exactlythe ones that you receive as a server and vice-versa.
`Here's an example of a tiny HTTP client<https://github.com/python-hyper/h11/blob/master/examples/basic-client.py>`_
It also has `a fine manual <https://h11.readthedocs.io/>`_.
FAQ---
*Whyyyyy?*
I wanted to play with HTTP in `Curio<https://curio.readthedocs.io/en/latest/tutorial.html>`__ and `Trio<https://trio.readthedocs.io>`__, which at the time didn't have anyHTTP libraries. So I thought, no big deal, Python has, like, a dozendifferent implementations of HTTP, surely I can find one that'sreusable. I didn't find one, but I did find Cory's call-to-armsblog-post. So I figured, well, fine, if I have to implement HTTP fromscratch, at least I can make sure no-one *else* has to ever again.
*Should I use it?*
Maybe. You should be aware that it's a very young project. But, it'sfeature complete and has an exhaustive test-suite and complete docs,so the next step is for people to try using it and see how it goes:-). If you do then please let us know -- if nothing else we'll wantto talk to you before making any incompatible changes!
*What are the features/limitations?*
Roughly speaking, it's trying to be a robust, complete, and non-hackyimplementation of the first "chapter" of the HTTP/1.1 spec: `RFC 7230:HTTP/1.1 Message Syntax and Routing<https://tools.ietf.org/html/rfc7230>`_. That is, it mostly focuses onimplementing HTTP at the level of taking bytes on and off the wire,and the headers related to that, and tries to be anal about specconformance. It doesn't know about higher-level concerns like URLrouting, conditional GETs, cross-origin cookie policies, or contentnegotiation. But it does know how to take care of framing,cross-version differences in keep-alive handling, and the "obsoleteline folding" rule, so you can focus your energies on the hard /interesting parts for your application, and it tries to support thefull specification in the sense that any useful HTTP/1.1 conformantapplication should be able to use h11.
It's pure Python, and has no dependencies outside of the standardlibrary.
It has a test suite with 100.0% coverage for both statements andbranches.
Currently it supports Python 3 (testing on 3.8-3.12) and PyPy 3.The last Python 2-compatible version was h11 0.11.x.(Originally it had a Cython wrapper for `http-parser<https://github.com/nodejs/http-parser>`_ and a beautiful nested statemachine implemented with ``yield from`` to postprocess the output. ButI had to take these out -- the new *parser* needs fewer lines-of-codethan the old *parser wrapper*, is written in pure Python, uses noexotic language syntax, and has more features. It's sad, really; thatold state machine was really slick. I just need a few sentences hereto mourn that.)
I don't know how fast it is. I haven't benchmarked or profiled it yet,so it's probably got a few pointless hot spots, and I've been tryingto err on the side of simplicity and robustness instead ofmicro-optimization. But at the architectural level I tried hard toavoid fundamentally bad decisions, e.g., I believe that all theparsing algorithms remain linear-time even in the face of pathologicalinput like slowloris, and there are no byte-by-byte loops. (I alsobelieve that it maintains bounded memory usage in the face ofarbitrary/pathological input.)
The whole library is ~800 lines-of-code. You can read and understandthe whole thing in less than an hour. Most of the energy invested inthis so far has been spent on trying to keep things simple byminimizing special-cases and ad hoc state manipulation; even though itis now quite small and simple, I'm still annoyed that I haven'tfigured out how to make it even smaller and simpler. (Unfortunately,HTTP does not lend itself to simplicity.)
The API is ~feature complete and I don't expect the general outlinesto change much, but you can't judge an API's ergonomics until youactually document and use it, so I'd expect some changes in thedetails.
*How do I try it?*
.. code-block:: sh
$ pip install h11 $ git clone git@github.com:python-hyper/h11 $ cd h11/examples $ python basic-client.py
and go from there.
*License?*
MIT
*Code of conduct?*
Contributors are requested to follow our `code of conduct<https://github.com/python-hyper/h11/blob/master/CODE_OF_CONDUCT.md>`_ inall project spaces.1234567891011121314151617181920212223242526272829h11-0.16.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
h11-0.16.0.dist-info/METADATA,sha256=KPMmCYrAn8unm48YD5YIfIQf4kViFct7hyqcfVzRnWQ,8348
h11-0.16.0.dist-info/RECORD,,
h11-0.16.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
h11-0.16.0.dist-info/licenses/LICENSE.txt,sha256=N9tbuFkm2yikJ6JYZ_ELEjIAOuob5pzLhRE4rbjm82E,1124
h11-0.16.0.dist-info/top_level.txt,sha256=F7dC4jl3zeh8TGHEPaWJrMbeuoWbS379Gwdi-Yvdcis,4
h11/__init__.py,sha256=iO1KzkSO42yZ6ffg-VMgbx_ZVTWGUY00nRYEWn-s3kY,1507
h11/__pycache__/__init__.cpython-312.pyc,,
h11/__pycache__/_abnf.cpython-312.pyc,,
h11/__pycache__/_connection.cpython-312.pyc,,
h11/__pycache__/_events.cpython-312.pyc,,
h11/__pycache__/_headers.cpython-312.pyc,,
h11/__pycache__/_readers.cpython-312.pyc,,
h11/__pycache__/_receivebuffer.cpython-312.pyc,,
h11/__pycache__/_state.cpython-312.pyc,,
h11/__pycache__/_util.cpython-312.pyc,,
h11/__pycache__/_version.cpython-312.pyc,,
h11/__pycache__/_writers.cpython-312.pyc,,
h11/_abnf.py,sha256=ybixr0xsupnkA6GFAyMubuXF6Tc1lb_hF890NgCsfNc,4815
h11/_connection.py,sha256=k9YRVf6koZqbttBW36xSWaJpWdZwa-xQVU9AHEo9DuI,26863
h11/_events.py,sha256=I97aXoal1Wu7dkL548BANBUCkOIbe-x5CioYA9IBY14,11792
h11/_headers.py,sha256=P7D-lBNxHwdLZPLimmYwrPG-9ZkjElvvJZJdZAgSP-4,10412
h11/_readers.py,sha256=a4RypORUCC3d0q_kxPuBIM7jTD8iLt5X91TH0FsduN4,8590
h11/_receivebuffer.py,sha256=xrspsdsNgWFxRfQcTXxR8RrdjRXXTK0Io5cQYWpJ1Ws,5252
h11/_state.py,sha256=_5LG_BGR8FCcFQeBPH-TMHgm_-B-EUcWCnQof_9XjFE,13231
h11/_util.py,sha256=LWkkjXyJaFlAy6Lt39w73UStklFT5ovcvo0TkY7RYuk,4888
h11/_version.py,sha256=GVSsbPSPDcOuF6ptfIiXnVJoaEm3ygXbMnqlr_Giahw,686
h11/_writers.py,sha256=oFKm6PtjeHfbj4RLX7VB7KDc1gIY53gXG3_HR9ltmTA,5081
h11/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,712345Wheel-Version: 1.0Generator: setuptools (78.1.0)Root-Is-Purelib: trueTag: py3-none-any
12345678910111213141516171819202122The MIT License (MIT)
Copyright (c) 2016 Nathaniel J. Smith <njs@pobox.com> and other contributors
Permission is hereby granted, free of charge, to any person obtaininga copy of this software and associated documentation files (the"Software"), to deal in the Software without restriction, includingwithout limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and topermit persons to whom the Software is furnished to do so, subject tothe following conditions:
The above copyright notice and this permission notice shall beincluded in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE ANDNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BELIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTIONOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTIONWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.1h11123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141from ._api import request, streamfrom ._async import ( AsyncConnectionInterface, AsyncConnectionPool, AsyncHTTP2Connection, AsyncHTTP11Connection, AsyncHTTPConnection, AsyncHTTPProxy, AsyncSOCKSProxy,)from ._backends.base import ( SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStream, NetworkBackend, NetworkStream,)from ._backends.mock import AsyncMockBackend, AsyncMockStream, MockBackend, MockStreamfrom ._backends.sync import SyncBackendfrom ._exceptions import ( ConnectError, ConnectionNotAvailable, ConnectTimeout, LocalProtocolError, NetworkError, PoolTimeout, ProtocolError, ProxyError, ReadError, ReadTimeout, RemoteProtocolError, TimeoutException, UnsupportedProtocol, WriteError, WriteTimeout,)from ._models import URL, Origin, Proxy, Request, Responsefrom ._ssl import default_ssl_contextfrom ._sync import ( ConnectionInterface, ConnectionPool, HTTP2Connection, HTTP11Connection, HTTPConnection, HTTPProxy, SOCKSProxy,)
# The 'httpcore.AnyIOBackend' class is conditional on 'anyio' being installed.try: from ._backends.anyio import AnyIOBackendexcept ImportError: # pragma: nocover
class AnyIOBackend: # type: ignore def __init__(self, *args, **kwargs): # type: ignore msg = ( "Attempted to use 'httpcore.AnyIOBackend' but 'anyio' is not installed." ) raise RuntimeError(msg)
# The 'httpcore.TrioBackend' class is conditional on 'trio' being installed.try: from ._backends.trio import TrioBackendexcept ImportError: # pragma: nocover
class TrioBackend: # type: ignore def __init__(self, *args, **kwargs): # type: ignore msg = "Attempted to use 'httpcore.TrioBackend' but 'trio' is not installed." raise RuntimeError(msg)
__all__ = [ # top-level requests "request", "stream", # models "Origin", "URL", "Request", "Response", "Proxy", # async "AsyncHTTPConnection", "AsyncConnectionPool", "AsyncHTTPProxy", "AsyncHTTP11Connection", "AsyncHTTP2Connection", "AsyncConnectionInterface", "AsyncSOCKSProxy", # sync "HTTPConnection", "ConnectionPool", "HTTPProxy", "HTTP11Connection", "HTTP2Connection", "ConnectionInterface", "SOCKSProxy", # network backends, implementations "SyncBackend", "AnyIOBackend", "TrioBackend", # network backends, mock implementations "AsyncMockBackend", "AsyncMockStream", "MockBackend", "MockStream", # network backends, interface "AsyncNetworkStream", "AsyncNetworkBackend", "NetworkStream", "NetworkBackend", # util "default_ssl_context", "SOCKET_OPTION", # exceptions "ConnectionNotAvailable", "ProxyError", "ProtocolError", "LocalProtocolError", "RemoteProtocolError", "UnsupportedProtocol", "TimeoutException", "PoolTimeout", "ConnectTimeout", "ReadTimeout", "WriteTimeout", "NetworkError", "ConnectError", "ReadError", "WriteError",]
__version__ = "1.0.9"
__locals = locals()for __name in __all__: # Exclude SOCKET_OPTION, it causes AttributeError on Python 3.14 if not __name.startswith(("__", "SOCKET_OPTION")): setattr(__locals[__name], "__module__", "httpcore") # noqa12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394from __future__ import annotations
import contextlibimport typing
from ._models import URL, Extensions, HeaderTypes, Responsefrom ._sync.connection_pool import ConnectionPool
def request( method: bytes | str, url: URL | bytes | str, *, headers: HeaderTypes = None, content: bytes | typing.Iterator[bytes] | None = None, extensions: Extensions | None = None,) -> Response: """ Sends an HTTP request, returning the response.
``` response = httpcore.request("GET", "https://www.example.com/") ```
Arguments: method: The HTTP method for the request. Typically one of `"GET"`, `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, or as str/bytes. headers: The HTTP request headers. Either as a dictionary of str/bytes, or as a list of two-tuples of str/bytes. content: The content of the request body. Either as bytes, or as a bytes iterator. extensions: A dictionary of optional extra information included on the request. Possible keys include `"timeout"`.
Returns: An instance of `httpcore.Response`. """ with ConnectionPool() as pool: return pool.request( method=method, url=url, headers=headers, content=content, extensions=extensions, )
@contextlib.contextmanagerdef stream( method: bytes | str, url: URL | bytes | str, *, headers: HeaderTypes = None, content: bytes | typing.Iterator[bytes] | None = None, extensions: Extensions | None = None,) -> typing.Iterator[Response]: """ Sends an HTTP request, returning the response within a content manager.
``` with httpcore.stream("GET", "https://www.example.com/") as response: ... ```
When using the `stream()` function, the body of the response will not be automatically read. If you want to access the response body you should either use `content = response.read()`, or `for chunk in response.iter_content()`.
Arguments: method: The HTTP method for the request. Typically one of `"GET"`, `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, or as str/bytes. headers: The HTTP request headers. Either as a dictionary of str/bytes, or as a list of two-tuples of str/bytes. content: The content of the request body. Either as bytes, or as a bytes iterator. extensions: A dictionary of optional extra information included on the request. Possible keys include `"timeout"`.
Returns: An instance of `httpcore.Response`. """ with ConnectionPool() as pool: with pool.stream( method=method, url=url, headers=headers, content=content, extensions=extensions, ) as response: yield response123456789101112131415161718192021222324252627282930313233343536373839from .connection import AsyncHTTPConnectionfrom .connection_pool import AsyncConnectionPoolfrom .http11 import AsyncHTTP11Connectionfrom .http_proxy import AsyncHTTPProxyfrom .interfaces import AsyncConnectionInterface
try: from .http2 import AsyncHTTP2Connectionexcept ImportError: # pragma: nocover
class AsyncHTTP2Connection: # type: ignore def __init__(self, *args, **kwargs) -> None: # type: ignore raise RuntimeError( "Attempted to use http2 support, but the `h2` package is not " "installed. Use 'pip install httpcore[http2]'." )
try: from .socks_proxy import AsyncSOCKSProxyexcept ImportError: # pragma: nocover
class AsyncSOCKSProxy: # type: ignore def __init__(self, *args, **kwargs) -> None: # type: ignore raise RuntimeError( "Attempted to use SOCKS support, but the `socksio` package is not " "installed. Use 'pip install httpcore[socks]'." )
__all__ = [ "AsyncHTTPConnection", "AsyncConnectionPool", "AsyncHTTPProxy", "AsyncHTTP11Connection", "AsyncHTTP2Connection", "AsyncConnectionInterface", "AsyncSOCKSProxy",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222from __future__ import annotations
import itertoolsimport loggingimport sslimport typesimport typing
from .._backends.auto import AutoBackendfrom .._backends.base import SOCKET_OPTION, AsyncNetworkBackend, AsyncNetworkStreamfrom .._exceptions import ConnectError, ConnectTimeoutfrom .._models import Origin, Request, Responsefrom .._ssl import default_ssl_contextfrom .._synchronization import AsyncLockfrom .._trace import Tracefrom .http11 import AsyncHTTP11Connectionfrom .interfaces import AsyncConnectionInterface
RETRIES_BACKOFF_FACTOR = 0.5 # 0s, 0.5s, 1s, 2s, 4s, etc.
logger = logging.getLogger("httpcore.connection")
def exponential_backoff(factor: float) -> typing.Iterator[float]: """ Generate a geometric sequence that has a ratio of 2 and starts with 0.
For example: - `factor = 2`: `0, 2, 4, 8, 16, 32, 64, ...` - `factor = 3`: `0, 3, 6, 12, 24, 48, 96, ...` """ yield 0 for n in itertools.count(): yield factor * 2**n
class AsyncHTTPConnection(AsyncConnectionInterface): def __init__( self, origin: Origin, ssl_context: ssl.SSLContext | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, retries: int = 0, local_address: str | None = None, uds: str | None = None, network_backend: AsyncNetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: self._origin = origin self._ssl_context = ssl_context self._keepalive_expiry = keepalive_expiry self._http1 = http1 self._http2 = http2 self._retries = retries self._local_address = local_address self._uds = uds
self._network_backend: AsyncNetworkBackend = ( AutoBackend() if network_backend is None else network_backend ) self._connection: AsyncConnectionInterface | None = None self._connect_failed: bool = False self._request_lock = AsyncLock() self._socket_options = socket_options
async def handle_async_request(self, request: Request) -> Response: if not self.can_handle_request(request.url.origin): raise RuntimeError( f"Attempted to send request to {request.url.origin} on connection to {self._origin}" )
try: async with self._request_lock: if self._connection is None: stream = await self._connect(request)
ssl_object = stream.get_extra_info("ssl_object") http2_negotiated = ( ssl_object is not None and ssl_object.selected_alpn_protocol() == "h2" ) if http2_negotiated or (self._http2 and not self._http1): from .http2 import AsyncHTTP2Connection
self._connection = AsyncHTTP2Connection( origin=self._origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) else: self._connection = AsyncHTTP11Connection( origin=self._origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) except BaseException as exc: self._connect_failed = True raise exc
return await self._connection.handle_async_request(request)
async def _connect(self, request: Request) -> AsyncNetworkStream: timeouts = request.extensions.get("timeout", {}) sni_hostname = request.extensions.get("sni_hostname", None) timeout = timeouts.get("connect", None)
retries_left = self._retries delays = exponential_backoff(factor=RETRIES_BACKOFF_FACTOR)
while True: try: if self._uds is None: kwargs = { "host": self._origin.host.decode("ascii"), "port": self._origin.port, "local_address": self._local_address, "timeout": timeout, "socket_options": self._socket_options, } async with Trace("connect_tcp", logger, request, kwargs) as trace: stream = await self._network_backend.connect_tcp(**kwargs) trace.return_value = stream else: kwargs = { "path": self._uds, "timeout": timeout, "socket_options": self._socket_options, } async with Trace( "connect_unix_socket", logger, request, kwargs ) as trace: stream = await self._network_backend.connect_unix_socket( **kwargs ) trace.return_value = stream
if self._origin.scheme in (b"https", b"wss"): ssl_context = ( default_ssl_context() if self._ssl_context is None else self._ssl_context ) alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] ssl_context.set_alpn_protocols(alpn_protocols)
kwargs = { "ssl_context": ssl_context, "server_hostname": sni_hostname or self._origin.host.decode("ascii"), "timeout": timeout, } async with Trace("start_tls", logger, request, kwargs) as trace: stream = await stream.start_tls(**kwargs) trace.return_value = stream return stream except (ConnectError, ConnectTimeout): if retries_left <= 0: raise retries_left -= 1 delay = next(delays) async with Trace("retry", logger, request, kwargs) as trace: await self._network_backend.sleep(delay)
def can_handle_request(self, origin: Origin) -> bool: return origin == self._origin
async def aclose(self) -> None: if self._connection is not None: async with Trace("close", logger, None, {}): await self._connection.aclose()
def is_available(self) -> bool: if self._connection is None: # If HTTP/2 support is enabled, and the resulting connection could # end up as HTTP/2 then we should indicate the connection as being # available to service multiple requests. return ( self._http2 and (self._origin.scheme == b"https" or not self._http1) and not self._connect_failed ) return self._connection.is_available()
def has_expired(self) -> bool: if self._connection is None: return self._connect_failed return self._connection.has_expired()
def is_idle(self) -> bool: if self._connection is None: return self._connect_failed return self._connection.is_idle()
def is_closed(self) -> bool: if self._connection is None: return self._connect_failed return self._connection.is_closed()
def info(self) -> str: if self._connection is None: return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" return self._connection.info()
def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.info()}]>"
# These context managers are not used in the standard flow, but are # useful for testing or working with connection instances directly.
async def __aenter__(self) -> AsyncHTTPConnection: return self
async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: await self.aclose()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420from __future__ import annotations
import sslimport sysimport typesimport typing
from .._backends.auto import AutoBackendfrom .._backends.base import SOCKET_OPTION, AsyncNetworkBackendfrom .._exceptions import ConnectionNotAvailable, UnsupportedProtocolfrom .._models import Origin, Proxy, Request, Responsefrom .._synchronization import AsyncEvent, AsyncShieldCancellation, AsyncThreadLockfrom .connection import AsyncHTTPConnectionfrom .interfaces import AsyncConnectionInterface, AsyncRequestInterface
class AsyncPoolRequest: def __init__(self, request: Request) -> None: self.request = request self.connection: AsyncConnectionInterface | None = None self._connection_acquired = AsyncEvent()
def assign_to_connection(self, connection: AsyncConnectionInterface | None) -> None: self.connection = connection self._connection_acquired.set()
def clear_connection(self) -> None: self.connection = None self._connection_acquired = AsyncEvent()
async def wait_for_connection( self, timeout: float | None = None ) -> AsyncConnectionInterface: if self.connection is None: await self._connection_acquired.wait(timeout=timeout) assert self.connection is not None return self.connection
def is_queued(self) -> bool: return self.connection is None
class AsyncConnectionPool(AsyncRequestInterface): """ A connection pool for making HTTP requests. """
def __init__( self, ssl_context: ssl.SSLContext | None = None, proxy: Proxy | None = None, max_connections: int | None = 10, max_keepalive_connections: int | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, retries: int = 0, local_address: str | None = None, uds: str | None = None, network_backend: AsyncNetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: """ A connection pool for making HTTP requests.
Parameters: ssl_context: An SSL context to use for verifying connections. If not specified, the default `httpcore.default_ssl_context()` will be used. max_connections: The maximum number of concurrent HTTP connections that the pool should allow. Any attempt to send a request on a pool that would exceed this amount will block until a connection is available. max_keepalive_connections: The maximum number of idle HTTP connections that will be maintained in the pool. keepalive_expiry: The duration in seconds that an idle HTTP connection may be maintained for before being expired from the pool. http1: A boolean indicating if HTTP/1.1 requests should be supported by the connection pool. Defaults to True. http2: A boolean indicating if HTTP/2 requests should be supported by the connection pool. Defaults to False. retries: The maximum number of retries when trying to establish a connection. local_address: Local address to connect from. Can also be used to connect using a particular address family. Using `local_address="0.0.0.0"` will connect using an `AF_INET` address (IPv4), while using `local_address="::"` will connect using an `AF_INET6` address (IPv6). uds: Path to a Unix Domain Socket to use instead of TCP sockets. network_backend: A backend instance to use for handling network I/O. socket_options: Socket options that have to be included in the TCP socket when the connection was established. """ self._ssl_context = ssl_context self._proxy = proxy self._max_connections = ( sys.maxsize if max_connections is None else max_connections ) self._max_keepalive_connections = ( sys.maxsize if max_keepalive_connections is None else max_keepalive_connections ) self._max_keepalive_connections = min( self._max_connections, self._max_keepalive_connections )
self._keepalive_expiry = keepalive_expiry self._http1 = http1 self._http2 = http2 self._retries = retries self._local_address = local_address self._uds = uds
self._network_backend = ( AutoBackend() if network_backend is None else network_backend ) self._socket_options = socket_options
# The mutable state on a connection pool is the queue of incoming requests, # and the set of connections that are servicing those requests. self._connections: list[AsyncConnectionInterface] = [] self._requests: list[AsyncPoolRequest] = []
# We only mutate the state of the connection pool within an 'optional_thread_lock' # context. This holds a threading lock unless we're running in async mode, # in which case it is a no-op. self._optional_thread_lock = AsyncThreadLock()
def create_connection(self, origin: Origin) -> AsyncConnectionInterface: if self._proxy is not None: if self._proxy.url.scheme in (b"socks5", b"socks5h"): from .socks_proxy import AsyncSocks5Connection
return AsyncSocks5Connection( proxy_origin=self._proxy.url.origin, proxy_auth=self._proxy.auth, remote_origin=origin, ssl_context=self._ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, network_backend=self._network_backend, ) elif origin.scheme == b"http": from .http_proxy import AsyncForwardHTTPConnection
return AsyncForwardHTTPConnection( proxy_origin=self._proxy.url.origin, proxy_headers=self._proxy.headers, proxy_ssl_context=self._proxy.ssl_context, remote_origin=origin, keepalive_expiry=self._keepalive_expiry, network_backend=self._network_backend, ) from .http_proxy import AsyncTunnelHTTPConnection
return AsyncTunnelHTTPConnection( proxy_origin=self._proxy.url.origin, proxy_headers=self._proxy.headers, proxy_ssl_context=self._proxy.ssl_context, remote_origin=origin, ssl_context=self._ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, network_backend=self._network_backend, )
return AsyncHTTPConnection( origin=origin, ssl_context=self._ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, retries=self._retries, local_address=self._local_address, uds=self._uds, network_backend=self._network_backend, socket_options=self._socket_options, )
@property def connections(self) -> list[AsyncConnectionInterface]: """ Return a list of the connections currently in the pool.
For example:
```python >>> pool.connections [ <AsyncHTTPConnection ['https://example.com:443', HTTP/1.1, ACTIVE, Request Count: 6]>, <AsyncHTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 9]> , <AsyncHTTPConnection ['http://example.com:80', HTTP/1.1, IDLE, Request Count: 1]>, ] ``` """ return list(self._connections)
async def handle_async_request(self, request: Request) -> Response: """ Send an HTTP request, and return an HTTP response.
This is the core implementation that is called into by `.request()` or `.stream()`. """ scheme = request.url.scheme.decode() if scheme == "": raise UnsupportedProtocol( "Request URL is missing an 'http://' or 'https://' protocol." ) if scheme not in ("http", "https", "ws", "wss"): raise UnsupportedProtocol( f"Request URL has an unsupported protocol '{scheme}://'." )
timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("pool", None)
with self._optional_thread_lock: # Add the incoming request to our request queue. pool_request = AsyncPoolRequest(request) self._requests.append(pool_request)
try: while True: with self._optional_thread_lock: # Assign incoming requests to available connections, # closing or creating new connections as required. closing = self._assign_requests_to_connections() await self._close_connections(closing)
# Wait until this request has an assigned connection. connection = await pool_request.wait_for_connection(timeout=timeout)
try: # Send the request on the assigned connection. response = await connection.handle_async_request( pool_request.request ) except ConnectionNotAvailable: # In some cases a connection may initially be available to # handle a request, but then become unavailable. # # In this case we clear the connection and try again. pool_request.clear_connection() else: break # pragma: nocover
except BaseException as exc: with self._optional_thread_lock: # For any exception or cancellation we remove the request from # the queue, and then re-assign requests to connections. self._requests.remove(pool_request) closing = self._assign_requests_to_connections()
await self._close_connections(closing) raise exc from None
# Return the response. Note that in this case we still have to manage # the point at which the response is closed. assert isinstance(response.stream, typing.AsyncIterable) return Response( status=response.status, headers=response.headers, content=PoolByteStream( stream=response.stream, pool_request=pool_request, pool=self ), extensions=response.extensions, )
def _assign_requests_to_connections(self) -> list[AsyncConnectionInterface]: """ Manage the state of the connection pool, assigning incoming requests to connections as available.
Called whenever a new request is added or removed from the pool.
Any closing connections are returned, allowing the I/O for closing those connections to be handled seperately. """ closing_connections = []
# First we handle cleaning up any connections that are closed, # have expired their keep-alive, or surplus idle connections. for connection in list(self._connections): if connection.is_closed(): # log: "removing closed connection" self._connections.remove(connection) elif connection.has_expired(): # log: "closing expired connection" self._connections.remove(connection) closing_connections.append(connection) elif ( connection.is_idle() and len([connection.is_idle() for connection in self._connections]) > self._max_keepalive_connections ): # log: "closing idle connection" self._connections.remove(connection) closing_connections.append(connection)
# Assign queued requests to connections. queued_requests = [request for request in self._requests if request.is_queued()] for pool_request in queued_requests: origin = pool_request.request.url.origin available_connections = [ connection for connection in self._connections if connection.can_handle_request(origin) and connection.is_available() ] idle_connections = [ connection for connection in self._connections if connection.is_idle() ]
# There are three cases for how we may be able to handle the request: # # 1. There is an existing connection that can handle the request. # 2. We can create a new connection to handle the request. # 3. We can close an idle connection and then create a new connection # to handle the request. if available_connections: # log: "reusing existing connection" connection = available_connections[0] pool_request.assign_to_connection(connection) elif len(self._connections) < self._max_connections: # log: "creating new connection" connection = self.create_connection(origin) self._connections.append(connection) pool_request.assign_to_connection(connection) elif idle_connections: # log: "closing idle connection" connection = idle_connections[0] self._connections.remove(connection) closing_connections.append(connection) # log: "creating new connection" connection = self.create_connection(origin) self._connections.append(connection) pool_request.assign_to_connection(connection)
return closing_connections
async def _close_connections(self, closing: list[AsyncConnectionInterface]) -> None: # Close connections which have been removed from the pool. with AsyncShieldCancellation(): for connection in closing: await connection.aclose()
async def aclose(self) -> None: # Explicitly close the connection pool. # Clears all existing requests and connections. with self._optional_thread_lock: closing_connections = list(self._connections) self._connections = [] await self._close_connections(closing_connections)
async def __aenter__(self) -> AsyncConnectionPool: return self
async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: await self.aclose()
def __repr__(self) -> str: class_name = self.__class__.__name__ with self._optional_thread_lock: request_is_queued = [request.is_queued() for request in self._requests] connection_is_idle = [ connection.is_idle() for connection in self._connections ]
num_active_requests = request_is_queued.count(False) num_queued_requests = request_is_queued.count(True) num_active_connections = connection_is_idle.count(False) num_idle_connections = connection_is_idle.count(True)
requests_info = ( f"Requests: {num_active_requests} active, {num_queued_requests} queued" ) connection_info = ( f"Connections: {num_active_connections} active, {num_idle_connections} idle" )
return f"<{class_name} [{requests_info} | {connection_info}]>"
class PoolByteStream: def __init__( self, stream: typing.AsyncIterable[bytes], pool_request: AsyncPoolRequest, pool: AsyncConnectionPool, ) -> None: self._stream = stream self._pool_request = pool_request self._pool = pool self._closed = False
async def __aiter__(self) -> typing.AsyncIterator[bytes]: try: async for part in self._stream: yield part except BaseException as exc: await self.aclose() raise exc from None
async def aclose(self) -> None: if not self._closed: self._closed = True with AsyncShieldCancellation(): if hasattr(self._stream, "aclose"): await self._stream.aclose()
with self._pool._optional_thread_lock: self._pool._requests.remove(self._pool_request) closing = self._pool._assign_requests_to_connections()
await self._pool._close_connections(closing)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379from __future__ import annotations
import enumimport loggingimport sslimport timeimport typesimport typing
import h11
from .._backends.base import AsyncNetworkStreamfrom .._exceptions import ( ConnectionNotAvailable, LocalProtocolError, RemoteProtocolError, WriteError, map_exceptions,)from .._models import Origin, Request, Responsefrom .._synchronization import AsyncLock, AsyncShieldCancellationfrom .._trace import Tracefrom .interfaces import AsyncConnectionInterface
logger = logging.getLogger("httpcore.http11")
# A subset of `h11.Event` types supported by `_send_event`H11SendEvent = typing.Union[ h11.Request, h11.Data, h11.EndOfMessage,]
class HTTPConnectionState(enum.IntEnum): NEW = 0 ACTIVE = 1 IDLE = 2 CLOSED = 3
class AsyncHTTP11Connection(AsyncConnectionInterface): READ_NUM_BYTES = 64 * 1024 MAX_INCOMPLETE_EVENT_SIZE = 100 * 1024
def __init__( self, origin: Origin, stream: AsyncNetworkStream, keepalive_expiry: float | None = None, ) -> None: self._origin = origin self._network_stream = stream self._keepalive_expiry: float | None = keepalive_expiry self._expire_at: float | None = None self._state = HTTPConnectionState.NEW self._state_lock = AsyncLock() self._request_count = 0 self._h11_state = h11.Connection( our_role=h11.CLIENT, max_incomplete_event_size=self.MAX_INCOMPLETE_EVENT_SIZE, )
async def handle_async_request(self, request: Request) -> Response: if not self.can_handle_request(request.url.origin): raise RuntimeError( f"Attempted to send request to {request.url.origin} on connection " f"to {self._origin}" )
async with self._state_lock: if self._state in (HTTPConnectionState.NEW, HTTPConnectionState.IDLE): self._request_count += 1 self._state = HTTPConnectionState.ACTIVE self._expire_at = None else: raise ConnectionNotAvailable()
try: kwargs = {"request": request} try: async with Trace( "send_request_headers", logger, request, kwargs ) as trace: await self._send_request_headers(**kwargs) async with Trace("send_request_body", logger, request, kwargs) as trace: await self._send_request_body(**kwargs) except WriteError: # If we get a write error while we're writing the request, # then we supress this error and move on to attempting to # read the response. Servers can sometimes close the request # pre-emptively and then respond with a well formed HTTP # error response. pass
async with Trace( "receive_response_headers", logger, request, kwargs ) as trace: ( http_version, status, reason_phrase, headers, trailing_data, ) = await self._receive_response_headers(**kwargs) trace.return_value = ( http_version, status, reason_phrase, headers, )
network_stream = self._network_stream
# CONNECT or Upgrade request if (status == 101) or ( (request.method == b"CONNECT") and (200 <= status < 300) ): network_stream = AsyncHTTP11UpgradeStream(network_stream, trailing_data)
return Response( status=status, headers=headers, content=HTTP11ConnectionByteStream(self, request), extensions={ "http_version": http_version, "reason_phrase": reason_phrase, "network_stream": network_stream, }, ) except BaseException as exc: with AsyncShieldCancellation(): async with Trace("response_closed", logger, request) as trace: await self._response_closed() raise exc
# Sending the request...
async def _send_request_headers(self, request: Request) -> None: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("write", None)
with map_exceptions({h11.LocalProtocolError: LocalProtocolError}): event = h11.Request( method=request.method, target=request.url.target, headers=request.headers, ) await self._send_event(event, timeout=timeout)
async def _send_request_body(self, request: Request) -> None: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("write", None)
assert isinstance(request.stream, typing.AsyncIterable) async for chunk in request.stream: event = h11.Data(data=chunk) await self._send_event(event, timeout=timeout)
await self._send_event(h11.EndOfMessage(), timeout=timeout)
async def _send_event(self, event: h11.Event, timeout: float | None = None) -> None: bytes_to_send = self._h11_state.send(event) if bytes_to_send is not None: await self._network_stream.write(bytes_to_send, timeout=timeout)
# Receiving the response...
async def _receive_response_headers( self, request: Request ) -> tuple[bytes, int, bytes, list[tuple[bytes, bytes]], bytes]: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("read", None)
while True: event = await self._receive_event(timeout=timeout) if isinstance(event, h11.Response): break if ( isinstance(event, h11.InformationalResponse) and event.status_code == 101 ): break
http_version = b"HTTP/" + event.http_version
# h11 version 0.11+ supports a `raw_items` interface to get the # raw header casing, rather than the enforced lowercase headers. headers = event.headers.raw_items()
trailing_data, _ = self._h11_state.trailing_data
return http_version, event.status_code, event.reason, headers, trailing_data
async def _receive_response_body( self, request: Request ) -> typing.AsyncIterator[bytes]: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("read", None)
while True: event = await self._receive_event(timeout=timeout) if isinstance(event, h11.Data): yield bytes(event.data) elif isinstance(event, (h11.EndOfMessage, h11.PAUSED)): break
async def _receive_event( self, timeout: float | None = None ) -> h11.Event | type[h11.PAUSED]: while True: with map_exceptions({h11.RemoteProtocolError: RemoteProtocolError}): event = self._h11_state.next_event()
if event is h11.NEED_DATA: data = await self._network_stream.read( self.READ_NUM_BYTES, timeout=timeout )
# If we feed this case through h11 we'll raise an exception like: # # httpcore.RemoteProtocolError: can't handle event type # ConnectionClosed when role=SERVER and state=SEND_RESPONSE # # Which is accurate, but not very informative from an end-user # perspective. Instead we handle this case distinctly and treat # it as a ConnectError. if data == b"" and self._h11_state.their_state == h11.SEND_RESPONSE: msg = "Server disconnected without sending a response." raise RemoteProtocolError(msg)
self._h11_state.receive_data(data) else: # mypy fails to narrow the type in the above if statement above return event # type: ignore[return-value]
async def _response_closed(self) -> None: async with self._state_lock: if ( self._h11_state.our_state is h11.DONE and self._h11_state.their_state is h11.DONE ): self._state = HTTPConnectionState.IDLE self._h11_state.start_next_cycle() if self._keepalive_expiry is not None: now = time.monotonic() self._expire_at = now + self._keepalive_expiry else: await self.aclose()
# Once the connection is no longer required...
async def aclose(self) -> None: # Note that this method unilaterally closes the connection, and does # not have any kind of locking in place around it. self._state = HTTPConnectionState.CLOSED await self._network_stream.aclose()
# The AsyncConnectionInterface methods provide information about the state of # the connection, allowing for a connection pooling implementation to # determine when to reuse and when to close the connection...
def can_handle_request(self, origin: Origin) -> bool: return origin == self._origin
def is_available(self) -> bool: # Note that HTTP/1.1 connections in the "NEW" state are not treated as # being "available". The control flow which created the connection will # be able to send an outgoing request, but the connection will not be # acquired from the connection pool for any other request. return self._state == HTTPConnectionState.IDLE
def has_expired(self) -> bool: now = time.monotonic() keepalive_expired = self._expire_at is not None and now > self._expire_at
# If the HTTP connection is idle but the socket is readable, then the # only valid state is that the socket is about to return b"", indicating # a server-initiated disconnect. server_disconnected = ( self._state == HTTPConnectionState.IDLE and self._network_stream.get_extra_info("is_readable") )
return keepalive_expired or server_disconnected
def is_idle(self) -> bool: return self._state == HTTPConnectionState.IDLE
def is_closed(self) -> bool: return self._state == HTTPConnectionState.CLOSED
def info(self) -> str: origin = str(self._origin) return ( f"{origin!r}, HTTP/1.1, {self._state.name}, " f"Request Count: {self._request_count}" )
def __repr__(self) -> str: class_name = self.__class__.__name__ origin = str(self._origin) return ( f"<{class_name} [{origin!r}, {self._state.name}, " f"Request Count: {self._request_count}]>" )
# These context managers are not used in the standard flow, but are # useful for testing or working with connection instances directly.
async def __aenter__(self) -> AsyncHTTP11Connection: return self
async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: await self.aclose()
class HTTP11ConnectionByteStream: def __init__(self, connection: AsyncHTTP11Connection, request: Request) -> None: self._connection = connection self._request = request self._closed = False
async def __aiter__(self) -> typing.AsyncIterator[bytes]: kwargs = {"request": self._request} try: async with Trace("receive_response_body", logger, self._request, kwargs): async for chunk in self._connection._receive_response_body(**kwargs): yield chunk except BaseException as exc: # If we get an exception while streaming the response, # we want to close the response (and possibly the connection) # before raising that exception. with AsyncShieldCancellation(): await self.aclose() raise exc
async def aclose(self) -> None: if not self._closed: self._closed = True async with Trace("response_closed", logger, self._request): await self._connection._response_closed()
class AsyncHTTP11UpgradeStream(AsyncNetworkStream): def __init__(self, stream: AsyncNetworkStream, leading_data: bytes) -> None: self._stream = stream self._leading_data = leading_data
async def read(self, max_bytes: int, timeout: float | None = None) -> bytes: if self._leading_data: buffer = self._leading_data[:max_bytes] self._leading_data = self._leading_data[max_bytes:] return buffer else: return await self._stream.read(max_bytes, timeout)
async def write(self, buffer: bytes, timeout: float | None = None) -> None: await self._stream.write(buffer, timeout)
async def aclose(self) -> None: await self._stream.aclose()
async def start_tls( self, ssl_context: ssl.SSLContext, server_hostname: str | None = None, timeout: float | None = None, ) -> AsyncNetworkStream: return await self._stream.start_tls(ssl_context, server_hostname, timeout)
def get_extra_info(self, info: str) -> typing.Any: return self._stream.get_extra_info(info)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592from __future__ import annotations
import enumimport loggingimport timeimport typesimport typing
import h2.configimport h2.connectionimport h2.eventsimport h2.exceptionsimport h2.settings
from .._backends.base import AsyncNetworkStreamfrom .._exceptions import ( ConnectionNotAvailable, LocalProtocolError, RemoteProtocolError,)from .._models import Origin, Request, Responsefrom .._synchronization import AsyncLock, AsyncSemaphore, AsyncShieldCancellationfrom .._trace import Tracefrom .interfaces import AsyncConnectionInterface
logger = logging.getLogger("httpcore.http2")
def has_body_headers(request: Request) -> bool: return any( k.lower() == b"content-length" or k.lower() == b"transfer-encoding" for k, v in request.headers )
class HTTPConnectionState(enum.IntEnum): ACTIVE = 1 IDLE = 2 CLOSED = 3
class AsyncHTTP2Connection(AsyncConnectionInterface): READ_NUM_BYTES = 64 * 1024 CONFIG = h2.config.H2Configuration(validate_inbound_headers=False)
def __init__( self, origin: Origin, stream: AsyncNetworkStream, keepalive_expiry: float | None = None, ): self._origin = origin self._network_stream = stream self._keepalive_expiry: float | None = keepalive_expiry self._h2_state = h2.connection.H2Connection(config=self.CONFIG) self._state = HTTPConnectionState.IDLE self._expire_at: float | None = None self._request_count = 0 self._init_lock = AsyncLock() self._state_lock = AsyncLock() self._read_lock = AsyncLock() self._write_lock = AsyncLock() self._sent_connection_init = False self._used_all_stream_ids = False self._connection_error = False
# Mapping from stream ID to response stream events. self._events: dict[ int, list[ h2.events.ResponseReceived | h2.events.DataReceived | h2.events.StreamEnded | h2.events.StreamReset, ], ] = {}
# Connection terminated events are stored as state since # we need to handle them for all streams. self._connection_terminated: h2.events.ConnectionTerminated | None = None
self._read_exception: Exception | None = None self._write_exception: Exception | None = None
async def handle_async_request(self, request: Request) -> Response: if not self.can_handle_request(request.url.origin): # This cannot occur in normal operation, since the connection pool # will only send requests on connections that handle them. # It's in place simply for resilience as a guard against incorrect # usage, for anyone working directly with httpcore connections. raise RuntimeError( f"Attempted to send request to {request.url.origin} on connection " f"to {self._origin}" )
async with self._state_lock: if self._state in (HTTPConnectionState.ACTIVE, HTTPConnectionState.IDLE): self._request_count += 1 self._expire_at = None self._state = HTTPConnectionState.ACTIVE else: raise ConnectionNotAvailable()
async with self._init_lock: if not self._sent_connection_init: try: sci_kwargs = {"request": request} async with Trace( "send_connection_init", logger, request, sci_kwargs ): await self._send_connection_init(**sci_kwargs) except BaseException as exc: with AsyncShieldCancellation(): await self.aclose() raise exc
self._sent_connection_init = True
# Initially start with just 1 until the remote server provides # its max_concurrent_streams value self._max_streams = 1
local_settings_max_streams = ( self._h2_state.local_settings.max_concurrent_streams ) self._max_streams_semaphore = AsyncSemaphore(local_settings_max_streams)
for _ in range(local_settings_max_streams - self._max_streams): await self._max_streams_semaphore.acquire()
await self._max_streams_semaphore.acquire()
try: stream_id = self._h2_state.get_next_available_stream_id() self._events[stream_id] = [] except h2.exceptions.NoAvailableStreamIDError: # pragma: nocover self._used_all_stream_ids = True self._request_count -= 1 raise ConnectionNotAvailable()
try: kwargs = {"request": request, "stream_id": stream_id} async with Trace("send_request_headers", logger, request, kwargs): await self._send_request_headers(request=request, stream_id=stream_id) async with Trace("send_request_body", logger, request, kwargs): await self._send_request_body(request=request, stream_id=stream_id) async with Trace( "receive_response_headers", logger, request, kwargs ) as trace: status, headers = await self._receive_response( request=request, stream_id=stream_id ) trace.return_value = (status, headers)
return Response( status=status, headers=headers, content=HTTP2ConnectionByteStream(self, request, stream_id=stream_id), extensions={ "http_version": b"HTTP/2", "network_stream": self._network_stream, "stream_id": stream_id, }, ) except BaseException as exc: # noqa: PIE786 with AsyncShieldCancellation(): kwargs = {"stream_id": stream_id} async with Trace("response_closed", logger, request, kwargs): await self._response_closed(stream_id=stream_id)
if isinstance(exc, h2.exceptions.ProtocolError): # One case where h2 can raise a protocol error is when a # closed frame has been seen by the state machine. # # This happens when one stream is reading, and encounters # a GOAWAY event. Other flows of control may then raise # a protocol error at any point they interact with the 'h2_state'. # # In this case we'll have stored the event, and should raise # it as a RemoteProtocolError. if self._connection_terminated: # pragma: nocover raise RemoteProtocolError(self._connection_terminated) # If h2 raises a protocol error in some other state then we # must somehow have made a protocol violation. raise LocalProtocolError(exc) # pragma: nocover
raise exc
async def _send_connection_init(self, request: Request) -> None: """ The HTTP/2 connection requires some initial setup before we can start using individual request/response streams on it. """ # Need to set these manually here instead of manipulating via # __setitem__() otherwise the H2Connection will emit SettingsUpdate # frames in addition to sending the undesired defaults. self._h2_state.local_settings = h2.settings.Settings( client=True, initial_values={ # Disable PUSH_PROMISE frames from the server since we don't do anything # with them for now. Maybe when we support caching? h2.settings.SettingCodes.ENABLE_PUSH: 0, # These two are taken from h2 for safe defaults h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 100, h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE: 65536, }, )
# Some websites (*cough* Yahoo *cough*) balk at this setting being # present in the initial handshake since it's not defined in the original # RFC despite the RFC mandating ignoring settings you don't know about. del self._h2_state.local_settings[ h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL ]
self._h2_state.initiate_connection() self._h2_state.increment_flow_control_window(2**24) await self._write_outgoing_data(request)
# Sending the request...
async def _send_request_headers(self, request: Request, stream_id: int) -> None: """ Send the request headers to a given stream ID. """ end_stream = not has_body_headers(request)
# In HTTP/2 the ':authority' pseudo-header is used instead of 'Host'. # In order to gracefully handle HTTP/1.1 and HTTP/2 we always require # HTTP/1.1 style headers, and map them appropriately if we end up on # an HTTP/2 connection. authority = [v for k, v in request.headers if k.lower() == b"host"][0]
headers = [ (b":method", request.method), (b":authority", authority), (b":scheme", request.url.scheme), (b":path", request.url.target), ] + [ (k.lower(), v) for k, v in request.headers if k.lower() not in ( b"host", b"transfer-encoding", ) ]
self._h2_state.send_headers(stream_id, headers, end_stream=end_stream) self._h2_state.increment_flow_control_window(2**24, stream_id=stream_id) await self._write_outgoing_data(request)
async def _send_request_body(self, request: Request, stream_id: int) -> None: """ Iterate over the request body sending it to a given stream ID. """ if not has_body_headers(request): return
assert isinstance(request.stream, typing.AsyncIterable) async for data in request.stream: await self._send_stream_data(request, stream_id, data) await self._send_end_stream(request, stream_id)
async def _send_stream_data( self, request: Request, stream_id: int, data: bytes ) -> None: """ Send a single chunk of data in one or more data frames. """ while data: max_flow = await self._wait_for_outgoing_flow(request, stream_id) chunk_size = min(len(data), max_flow) chunk, data = data[:chunk_size], data[chunk_size:] self._h2_state.send_data(stream_id, chunk) await self._write_outgoing_data(request)
async def _send_end_stream(self, request: Request, stream_id: int) -> None: """ Send an empty data frame on on a given stream ID with the END_STREAM flag set. """ self._h2_state.end_stream(stream_id) await self._write_outgoing_data(request)
# Receiving the response...
async def _receive_response( self, request: Request, stream_id: int ) -> tuple[int, list[tuple[bytes, bytes]]]: """ Return the response status code and headers for a given stream ID. """ while True: event = await self._receive_stream_event(request, stream_id) if isinstance(event, h2.events.ResponseReceived): break
status_code = 200 headers = [] assert event.headers is not None for k, v in event.headers: if k == b":status": status_code = int(v.decode("ascii", errors="ignore")) elif not k.startswith(b":"): headers.append((k, v))
return (status_code, headers)
async def _receive_response_body( self, request: Request, stream_id: int ) -> typing.AsyncIterator[bytes]: """ Iterator that returns the bytes of the response body for a given stream ID. """ while True: event = await self._receive_stream_event(request, stream_id) if isinstance(event, h2.events.DataReceived): assert event.flow_controlled_length is not None assert event.data is not None amount = event.flow_controlled_length self._h2_state.acknowledge_received_data(amount, stream_id) await self._write_outgoing_data(request) yield event.data elif isinstance(event, h2.events.StreamEnded): break
async def _receive_stream_event( self, request: Request, stream_id: int ) -> h2.events.ResponseReceived | h2.events.DataReceived | h2.events.StreamEnded: """ Return the next available event for a given stream ID.
Will read more data from the network if required. """ while not self._events.get(stream_id): await self._receive_events(request, stream_id) event = self._events[stream_id].pop(0) if isinstance(event, h2.events.StreamReset): raise RemoteProtocolError(event) return event
async def _receive_events( self, request: Request, stream_id: int | None = None ) -> None: """ Read some data from the network until we see one or more events for a given stream ID. """ async with self._read_lock: if self._connection_terminated is not None: last_stream_id = self._connection_terminated.last_stream_id if stream_id and last_stream_id and stream_id > last_stream_id: self._request_count -= 1 raise ConnectionNotAvailable() raise RemoteProtocolError(self._connection_terminated)
# This conditional is a bit icky. We don't want to block reading if we've # actually got an event to return for a given stream. We need to do that # check *within* the atomic read lock. Though it also need to be optional, # because when we call it from `_wait_for_outgoing_flow` we *do* want to # block until we've available flow control, event when we have events # pending for the stream ID we're attempting to send on. if stream_id is None or not self._events.get(stream_id): events = await self._read_incoming_data(request) for event in events: if isinstance(event, h2.events.RemoteSettingsChanged): async with Trace( "receive_remote_settings", logger, request ) as trace: await self._receive_remote_settings_change(event) trace.return_value = event
elif isinstance( event, ( h2.events.ResponseReceived, h2.events.DataReceived, h2.events.StreamEnded, h2.events.StreamReset, ), ): if event.stream_id in self._events: self._events[event.stream_id].append(event)
elif isinstance(event, h2.events.ConnectionTerminated): self._connection_terminated = event
await self._write_outgoing_data(request)
async def _receive_remote_settings_change( self, event: h2.events.RemoteSettingsChanged ) -> None: max_concurrent_streams = event.changed_settings.get( h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS ) if max_concurrent_streams: new_max_streams = min( max_concurrent_streams.new_value, self._h2_state.local_settings.max_concurrent_streams, ) if new_max_streams and new_max_streams != self._max_streams: while new_max_streams > self._max_streams: await self._max_streams_semaphore.release() self._max_streams += 1 while new_max_streams < self._max_streams: await self._max_streams_semaphore.acquire() self._max_streams -= 1
async def _response_closed(self, stream_id: int) -> None: await self._max_streams_semaphore.release() del self._events[stream_id] async with self._state_lock: if self._connection_terminated and not self._events: await self.aclose()
elif self._state == HTTPConnectionState.ACTIVE and not self._events: self._state = HTTPConnectionState.IDLE if self._keepalive_expiry is not None: now = time.monotonic() self._expire_at = now + self._keepalive_expiry if self._used_all_stream_ids: # pragma: nocover await self.aclose()
async def aclose(self) -> None: # Note that this method unilaterally closes the connection, and does # not have any kind of locking in place around it. self._h2_state.close_connection() self._state = HTTPConnectionState.CLOSED await self._network_stream.aclose()
# Wrappers around network read/write operations...
async def _read_incoming_data(self, request: Request) -> list[h2.events.Event]: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("read", None)
if self._read_exception is not None: raise self._read_exception # pragma: nocover
try: data = await self._network_stream.read(self.READ_NUM_BYTES, timeout) if data == b"": raise RemoteProtocolError("Server disconnected") except Exception as exc: # If we get a network error we should: # # 1. Save the exception and just raise it immediately on any future reads. # (For example, this means that a single read timeout or disconnect will # immediately close all pending streams. Without requiring multiple # sequential timeouts.) # 2. Mark the connection as errored, so that we don't accept any other # incoming requests. self._read_exception = exc self._connection_error = True raise exc
events: list[h2.events.Event] = self._h2_state.receive_data(data)
return events
async def _write_outgoing_data(self, request: Request) -> None: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("write", None)
async with self._write_lock: data_to_send = self._h2_state.data_to_send()
if self._write_exception is not None: raise self._write_exception # pragma: nocover
try: await self._network_stream.write(data_to_send, timeout) except Exception as exc: # pragma: nocover # If we get a network error we should: # # 1. Save the exception and just raise it immediately on any future write. # (For example, this means that a single write timeout or disconnect will # immediately close all pending streams. Without requiring multiple # sequential timeouts.) # 2. Mark the connection as errored, so that we don't accept any other # incoming requests. self._write_exception = exc self._connection_error = True raise exc
# Flow control...
async def _wait_for_outgoing_flow(self, request: Request, stream_id: int) -> int: """ Returns the maximum allowable outgoing flow for a given stream.
If the allowable flow is zero, then waits on the network until WindowUpdated frames have increased the flow rate. https://tools.ietf.org/html/rfc7540#section-6.9 """ local_flow: int = self._h2_state.local_flow_control_window(stream_id) max_frame_size: int = self._h2_state.max_outbound_frame_size flow = min(local_flow, max_frame_size) while flow == 0: await self._receive_events(request) local_flow = self._h2_state.local_flow_control_window(stream_id) max_frame_size = self._h2_state.max_outbound_frame_size flow = min(local_flow, max_frame_size) return flow
# Interface for connection pooling...
def can_handle_request(self, origin: Origin) -> bool: return origin == self._origin
def is_available(self) -> bool: return ( self._state != HTTPConnectionState.CLOSED and not self._connection_error and not self._used_all_stream_ids and not ( self._h2_state.state_machine.state == h2.connection.ConnectionState.CLOSED ) )
def has_expired(self) -> bool: now = time.monotonic() return self._expire_at is not None and now > self._expire_at
def is_idle(self) -> bool: return self._state == HTTPConnectionState.IDLE
def is_closed(self) -> bool: return self._state == HTTPConnectionState.CLOSED
def info(self) -> str: origin = str(self._origin) return ( f"{origin!r}, HTTP/2, {self._state.name}, " f"Request Count: {self._request_count}" )
def __repr__(self) -> str: class_name = self.__class__.__name__ origin = str(self._origin) return ( f"<{class_name} [{origin!r}, {self._state.name}, " f"Request Count: {self._request_count}]>" )
# These context managers are not used in the standard flow, but are # useful for testing or working with connection instances directly.
async def __aenter__(self) -> AsyncHTTP2Connection: return self
async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, ) -> None: await self.aclose()
class HTTP2ConnectionByteStream: def __init__( self, connection: AsyncHTTP2Connection, request: Request, stream_id: int ) -> None: self._connection = connection self._request = request self._stream_id = stream_id self._closed = False
async def __aiter__(self) -> typing.AsyncIterator[bytes]: kwargs = {"request": self._request, "stream_id": self._stream_id} try: async with Trace("receive_response_body", logger, self._request, kwargs): async for chunk in self._connection._receive_response_body( request=self._request, stream_id=self._stream_id ): yield chunk except BaseException as exc: # If we get an exception while streaming the response, # we want to close the response (and possibly the connection) # before raising that exception. with AsyncShieldCancellation(): await self.aclose() raise exc
async def aclose(self) -> None: if not self._closed: self._closed = True kwargs = {"stream_id": self._stream_id} async with Trace("response_closed", logger, self._request, kwargs): await self._connection._response_closed(stream_id=self._stream_id)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367from __future__ import annotations
import base64import loggingimport sslimport typing
from .._backends.base import SOCKET_OPTION, AsyncNetworkBackendfrom .._exceptions import ProxyErrorfrom .._models import ( URL, Origin, Request, Response, enforce_bytes, enforce_headers, enforce_url,)from .._ssl import default_ssl_contextfrom .._synchronization import AsyncLockfrom .._trace import Tracefrom .connection import AsyncHTTPConnectionfrom .connection_pool import AsyncConnectionPoolfrom .http11 import AsyncHTTP11Connectionfrom .interfaces import AsyncConnectionInterface
ByteOrStr = typing.Union[bytes, str]HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]]HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr]
logger = logging.getLogger("httpcore.proxy")
def merge_headers( default_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, override_headers: typing.Sequence[tuple[bytes, bytes]] | None = None,) -> list[tuple[bytes, bytes]]: """ Append default_headers and override_headers, de-duplicating if a key exists in both cases. """ default_headers = [] if default_headers is None else list(default_headers) override_headers = [] if override_headers is None else list(override_headers) has_override = set(key.lower() for key, value in override_headers) default_headers = [ (key, value) for key, value in default_headers if key.lower() not in has_override ] return default_headers + override_headers
class AsyncHTTPProxy(AsyncConnectionPool): # pragma: nocover """ A connection pool that sends requests via an HTTP proxy. """
def __init__( self, proxy_url: URL | bytes | str, proxy_auth: tuple[bytes | str, bytes | str] | None = None, proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, ssl_context: ssl.SSLContext | None = None, proxy_ssl_context: ssl.SSLContext | None = None, max_connections: int | None = 10, max_keepalive_connections: int | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, retries: int = 0, local_address: str | None = None, uds: str | None = None, network_backend: AsyncNetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: """ A connection pool for making HTTP requests.
Parameters: proxy_url: The URL to use when connecting to the proxy server. For example `"http://127.0.0.1:8080/"`. proxy_auth: Any proxy authentication as a two-tuple of (username, password). May be either bytes or ascii-only str. proxy_headers: Any HTTP headers to use for the proxy requests. For example `{"Proxy-Authorization": "Basic <username>:<password>"}`. ssl_context: An SSL context to use for verifying connections. If not specified, the default `httpcore.default_ssl_context()` will be used. proxy_ssl_context: The same as `ssl_context`, but for a proxy server rather than a remote origin. max_connections: The maximum number of concurrent HTTP connections that the pool should allow. Any attempt to send a request on a pool that would exceed this amount will block until a connection is available. max_keepalive_connections: The maximum number of idle HTTP connections that will be maintained in the pool. keepalive_expiry: The duration in seconds that an idle HTTP connection may be maintained for before being expired from the pool. http1: A boolean indicating if HTTP/1.1 requests should be supported by the connection pool. Defaults to True. http2: A boolean indicating if HTTP/2 requests should be supported by the connection pool. Defaults to False. retries: The maximum number of retries when trying to establish a connection. local_address: Local address to connect from. Can also be used to connect using a particular address family. Using `local_address="0.0.0.0"` will connect using an `AF_INET` address (IPv4), while using `local_address="::"` will connect using an `AF_INET6` address (IPv6). uds: Path to a Unix Domain Socket to use instead of TCP sockets. network_backend: A backend instance to use for handling network I/O. """ super().__init__( ssl_context=ssl_context, max_connections=max_connections, max_keepalive_connections=max_keepalive_connections, keepalive_expiry=keepalive_expiry, http1=http1, http2=http2, network_backend=network_backend, retries=retries, local_address=local_address, uds=uds, socket_options=socket_options, )
self._proxy_url = enforce_url(proxy_url, name="proxy_url") if ( self._proxy_url.scheme == b"http" and proxy_ssl_context is not None ): # pragma: no cover raise RuntimeError( "The `proxy_ssl_context` argument is not allowed for the http scheme" )
self._ssl_context = ssl_context self._proxy_ssl_context = proxy_ssl_context self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") if proxy_auth is not None: username = enforce_bytes(proxy_auth[0], name="proxy_auth") password = enforce_bytes(proxy_auth[1], name="proxy_auth") userpass = username + b":" + password authorization = b"Basic " + base64.b64encode(userpass) self._proxy_headers = [ (b"Proxy-Authorization", authorization) ] + self._proxy_headers
def create_connection(self, origin: Origin) -> AsyncConnectionInterface: if origin.scheme == b"http": return AsyncForwardHTTPConnection( proxy_origin=self._proxy_url.origin, proxy_headers=self._proxy_headers, remote_origin=origin, keepalive_expiry=self._keepalive_expiry, network_backend=self._network_backend, proxy_ssl_context=self._proxy_ssl_context, ) return AsyncTunnelHTTPConnection( proxy_origin=self._proxy_url.origin, proxy_headers=self._proxy_headers, remote_origin=origin, ssl_context=self._ssl_context, proxy_ssl_context=self._proxy_ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, network_backend=self._network_backend, )
class AsyncForwardHTTPConnection(AsyncConnectionInterface): def __init__( self, proxy_origin: Origin, remote_origin: Origin, proxy_headers: HeadersAsMapping | HeadersAsSequence | None = None, keepalive_expiry: float | None = None, network_backend: AsyncNetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, proxy_ssl_context: ssl.SSLContext | None = None, ) -> None: self._connection = AsyncHTTPConnection( origin=proxy_origin, keepalive_expiry=keepalive_expiry, network_backend=network_backend, socket_options=socket_options, ssl_context=proxy_ssl_context, ) self._proxy_origin = proxy_origin self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") self._remote_origin = remote_origin
async def handle_async_request(self, request: Request) -> Response: headers = merge_headers(self._proxy_headers, request.headers) url = URL( scheme=self._proxy_origin.scheme, host=self._proxy_origin.host, port=self._proxy_origin.port, target=bytes(request.url), ) proxy_request = Request( method=request.method, url=url, headers=headers, content=request.stream, extensions=request.extensions, ) return await self._connection.handle_async_request(proxy_request)
def can_handle_request(self, origin: Origin) -> bool: return origin == self._remote_origin
async def aclose(self) -> None: await self._connection.aclose()
def info(self) -> str: return self._connection.info()
def is_available(self) -> bool: return self._connection.is_available()
def has_expired(self) -> bool: return self._connection.has_expired()
def is_idle(self) -> bool: return self._connection.is_idle()
def is_closed(self) -> bool: return self._connection.is_closed()
def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.info()}]>"
class AsyncTunnelHTTPConnection(AsyncConnectionInterface): def __init__( self, proxy_origin: Origin, remote_origin: Origin, ssl_context: ssl.SSLContext | None = None, proxy_ssl_context: ssl.SSLContext | None = None, proxy_headers: typing.Sequence[tuple[bytes, bytes]] | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, network_backend: AsyncNetworkBackend | None = None, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: self._connection: AsyncConnectionInterface = AsyncHTTPConnection( origin=proxy_origin, keepalive_expiry=keepalive_expiry, network_backend=network_backend, socket_options=socket_options, ssl_context=proxy_ssl_context, ) self._proxy_origin = proxy_origin self._remote_origin = remote_origin self._ssl_context = ssl_context self._proxy_ssl_context = proxy_ssl_context self._proxy_headers = enforce_headers(proxy_headers, name="proxy_headers") self._keepalive_expiry = keepalive_expiry self._http1 = http1 self._http2 = http2 self._connect_lock = AsyncLock() self._connected = False
async def handle_async_request(self, request: Request) -> Response: timeouts = request.extensions.get("timeout", {}) timeout = timeouts.get("connect", None)
async with self._connect_lock: if not self._connected: target = b"%b:%d" % (self._remote_origin.host, self._remote_origin.port)
connect_url = URL( scheme=self._proxy_origin.scheme, host=self._proxy_origin.host, port=self._proxy_origin.port, target=target, ) connect_headers = merge_headers( [(b"Host", target), (b"Accept", b"*/*")], self._proxy_headers ) connect_request = Request( method=b"CONNECT", url=connect_url, headers=connect_headers, extensions=request.extensions, ) connect_response = await self._connection.handle_async_request( connect_request )
if connect_response.status < 200 or connect_response.status > 299: reason_bytes = connect_response.extensions.get("reason_phrase", b"") reason_str = reason_bytes.decode("ascii", errors="ignore") msg = "%d %s" % (connect_response.status, reason_str) await self._connection.aclose() raise ProxyError(msg)
stream = connect_response.extensions["network_stream"]
# Upgrade the stream to SSL ssl_context = ( default_ssl_context() if self._ssl_context is None else self._ssl_context ) alpn_protocols = ["http/1.1", "h2"] if self._http2 else ["http/1.1"] ssl_context.set_alpn_protocols(alpn_protocols)
kwargs = { "ssl_context": ssl_context, "server_hostname": self._remote_origin.host.decode("ascii"), "timeout": timeout, } async with Trace("start_tls", logger, request, kwargs) as trace: stream = await stream.start_tls(**kwargs) trace.return_value = stream
# Determine if we should be using HTTP/1.1 or HTTP/2 ssl_object = stream.get_extra_info("ssl_object") http2_negotiated = ( ssl_object is not None and ssl_object.selected_alpn_protocol() == "h2" )
# Create the HTTP/1.1 or HTTP/2 connection if http2_negotiated or (self._http2 and not self._http1): from .http2 import AsyncHTTP2Connection
self._connection = AsyncHTTP2Connection( origin=self._remote_origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) else: self._connection = AsyncHTTP11Connection( origin=self._remote_origin, stream=stream, keepalive_expiry=self._keepalive_expiry, )
self._connected = True return await self._connection.handle_async_request(request)
def can_handle_request(self, origin: Origin) -> bool: return origin == self._remote_origin
async def aclose(self) -> None: await self._connection.aclose()
def info(self) -> str: return self._connection.info()
def is_available(self) -> bool: return self._connection.is_available()
def has_expired(self) -> bool: return self._connection.has_expired()
def is_idle(self) -> bool: return self._connection.is_idle()
def is_closed(self) -> bool: return self._connection.is_closed()
def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.info()}]>"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137from __future__ import annotations
import contextlibimport typing
from .._models import ( URL, Extensions, HeaderTypes, Origin, Request, Response, enforce_bytes, enforce_headers, enforce_url, include_request_headers,)
class AsyncRequestInterface: async def request( self, method: bytes | str, url: URL | bytes | str, *, headers: HeaderTypes = None, content: bytes | typing.AsyncIterator[bytes] | None = None, extensions: Extensions | None = None, ) -> Response: # Strict type checking on our parameters. method = enforce_bytes(method, name="method") url = enforce_url(url, name="url") headers = enforce_headers(headers, name="headers")
# Include Host header, and optionally Content-Length or Transfer-Encoding. headers = include_request_headers(headers, url=url, content=content)
request = Request( method=method, url=url, headers=headers, content=content, extensions=extensions, ) response = await self.handle_async_request(request) try: await response.aread() finally: await response.aclose() return response
@contextlib.asynccontextmanager async def stream( self, method: bytes | str, url: URL | bytes | str, *, headers: HeaderTypes = None, content: bytes | typing.AsyncIterator[bytes] | None = None, extensions: Extensions | None = None, ) -> typing.AsyncIterator[Response]: # Strict type checking on our parameters. method = enforce_bytes(method, name="method") url = enforce_url(url, name="url") headers = enforce_headers(headers, name="headers")
# Include Host header, and optionally Content-Length or Transfer-Encoding. headers = include_request_headers(headers, url=url, content=content)
request = Request( method=method, url=url, headers=headers, content=content, extensions=extensions, ) response = await self.handle_async_request(request) try: yield response finally: await response.aclose()
async def handle_async_request(self, request: Request) -> Response: raise NotImplementedError() # pragma: nocover
class AsyncConnectionInterface(AsyncRequestInterface): async def aclose(self) -> None: raise NotImplementedError() # pragma: nocover
def info(self) -> str: raise NotImplementedError() # pragma: nocover
def can_handle_request(self, origin: Origin) -> bool: raise NotImplementedError() # pragma: nocover
def is_available(self) -> bool: """ Return `True` if the connection is currently able to accept an outgoing request.
An HTTP/1.1 connection will only be available if it is currently idle.
An HTTP/2 connection will be available so long as the stream ID space is not yet exhausted, and the connection is not in an error state.
While the connection is being established we may not yet know if it is going to result in an HTTP/1.1 or HTTP/2 connection. The connection should be treated as being available, but might ultimately raise `NewConnectionRequired` required exceptions if multiple requests are attempted over a connection that ends up being established as HTTP/1.1. """ raise NotImplementedError() # pragma: nocover
def has_expired(self) -> bool: """ Return `True` if the connection is in a state where it should be closed.
This either means that the connection is idle and it has passed the expiry time on its keep-alive, or that server has sent an EOF. """ raise NotImplementedError() # pragma: nocover
def is_idle(self) -> bool: """ Return `True` if the connection is currently idle. """ raise NotImplementedError() # pragma: nocover
def is_closed(self) -> bool: """ Return `True` if the connection has been closed.
Used when a response is closed to determine if the connection may be returned to the connection pool or not. """ raise NotImplementedError() # pragma: nocover123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341from __future__ import annotations
import loggingimport ssl
import socksio
from .._backends.auto import AutoBackendfrom .._backends.base import AsyncNetworkBackend, AsyncNetworkStreamfrom .._exceptions import ConnectionNotAvailable, ProxyErrorfrom .._models import URL, Origin, Request, Response, enforce_bytes, enforce_urlfrom .._ssl import default_ssl_contextfrom .._synchronization import AsyncLockfrom .._trace import Tracefrom .connection_pool import AsyncConnectionPoolfrom .http11 import AsyncHTTP11Connectionfrom .interfaces import AsyncConnectionInterface
logger = logging.getLogger("httpcore.socks")
AUTH_METHODS = { b"\x00": "NO AUTHENTICATION REQUIRED", b"\x01": "GSSAPI", b"\x02": "USERNAME/PASSWORD", b"\xff": "NO ACCEPTABLE METHODS",}
REPLY_CODES = { b"\x00": "Succeeded", b"\x01": "General SOCKS server failure", b"\x02": "Connection not allowed by ruleset", b"\x03": "Network unreachable", b"\x04": "Host unreachable", b"\x05": "Connection refused", b"\x06": "TTL expired", b"\x07": "Command not supported", b"\x08": "Address type not supported",}
async def _init_socks5_connection( stream: AsyncNetworkStream, *, host: bytes, port: int, auth: tuple[bytes, bytes] | None = None,) -> None: conn = socksio.socks5.SOCKS5Connection()
# Auth method request auth_method = ( socksio.socks5.SOCKS5AuthMethod.NO_AUTH_REQUIRED if auth is None else socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD ) conn.send(socksio.socks5.SOCKS5AuthMethodsRequest([auth_method])) outgoing_bytes = conn.data_to_send() await stream.write(outgoing_bytes)
# Auth method response incoming_bytes = await stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) assert isinstance(response, socksio.socks5.SOCKS5AuthReply) if response.method != auth_method: requested = AUTH_METHODS.get(auth_method, "UNKNOWN") responded = AUTH_METHODS.get(response.method, "UNKNOWN") raise ProxyError( f"Requested {requested} from proxy server, but got {responded}." )
if response.method == socksio.socks5.SOCKS5AuthMethod.USERNAME_PASSWORD: # Username/password request assert auth is not None username, password = auth conn.send(socksio.socks5.SOCKS5UsernamePasswordRequest(username, password)) outgoing_bytes = conn.data_to_send() await stream.write(outgoing_bytes)
# Username/password response incoming_bytes = await stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) assert isinstance(response, socksio.socks5.SOCKS5UsernamePasswordReply) if not response.success: raise ProxyError("Invalid username/password")
# Connect request conn.send( socksio.socks5.SOCKS5CommandRequest.from_address( socksio.socks5.SOCKS5Command.CONNECT, (host, port) ) ) outgoing_bytes = conn.data_to_send() await stream.write(outgoing_bytes)
# Connect response incoming_bytes = await stream.read(max_bytes=4096) response = conn.receive_data(incoming_bytes) assert isinstance(response, socksio.socks5.SOCKS5Reply) if response.reply_code != socksio.socks5.SOCKS5ReplyCode.SUCCEEDED: reply_code = REPLY_CODES.get(response.reply_code, "UNKOWN") raise ProxyError(f"Proxy Server could not connect: {reply_code}.")
class AsyncSOCKSProxy(AsyncConnectionPool): # pragma: nocover """ A connection pool that sends requests via an HTTP proxy. """
def __init__( self, proxy_url: URL | bytes | str, proxy_auth: tuple[bytes | str, bytes | str] | None = None, ssl_context: ssl.SSLContext | None = None, max_connections: int | None = 10, max_keepalive_connections: int | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, retries: int = 0, network_backend: AsyncNetworkBackend | None = None, ) -> None: """ A connection pool for making HTTP requests.
Parameters: proxy_url: The URL to use when connecting to the proxy server. For example `"http://127.0.0.1:8080/"`. ssl_context: An SSL context to use for verifying connections. If not specified, the default `httpcore.default_ssl_context()` will be used. max_connections: The maximum number of concurrent HTTP connections that the pool should allow. Any attempt to send a request on a pool that would exceed this amount will block until a connection is available. max_keepalive_connections: The maximum number of idle HTTP connections that will be maintained in the pool. keepalive_expiry: The duration in seconds that an idle HTTP connection may be maintained for before being expired from the pool. http1: A boolean indicating if HTTP/1.1 requests should be supported by the connection pool. Defaults to True. http2: A boolean indicating if HTTP/2 requests should be supported by the connection pool. Defaults to False. retries: The maximum number of retries when trying to establish a connection. local_address: Local address to connect from. Can also be used to connect using a particular address family. Using `local_address="0.0.0.0"` will connect using an `AF_INET` address (IPv4), while using `local_address="::"` will connect using an `AF_INET6` address (IPv6). uds: Path to a Unix Domain Socket to use instead of TCP sockets. network_backend: A backend instance to use for handling network I/O. """ super().__init__( ssl_context=ssl_context, max_connections=max_connections, max_keepalive_connections=max_keepalive_connections, keepalive_expiry=keepalive_expiry, http1=http1, http2=http2, network_backend=network_backend, retries=retries, ) self._ssl_context = ssl_context self._proxy_url = enforce_url(proxy_url, name="proxy_url") if proxy_auth is not None: username, password = proxy_auth username_bytes = enforce_bytes(username, name="proxy_auth") password_bytes = enforce_bytes(password, name="proxy_auth") self._proxy_auth: tuple[bytes, bytes] | None = ( username_bytes, password_bytes, ) else: self._proxy_auth = None
def create_connection(self, origin: Origin) -> AsyncConnectionInterface: return AsyncSocks5Connection( proxy_origin=self._proxy_url.origin, remote_origin=origin, proxy_auth=self._proxy_auth, ssl_context=self._ssl_context, keepalive_expiry=self._keepalive_expiry, http1=self._http1, http2=self._http2, network_backend=self._network_backend, )
class AsyncSocks5Connection(AsyncConnectionInterface): def __init__( self, proxy_origin: Origin, remote_origin: Origin, proxy_auth: tuple[bytes, bytes] | None = None, ssl_context: ssl.SSLContext | None = None, keepalive_expiry: float | None = None, http1: bool = True, http2: bool = False, network_backend: AsyncNetworkBackend | None = None, ) -> None: self._proxy_origin = proxy_origin self._remote_origin = remote_origin self._proxy_auth = proxy_auth self._ssl_context = ssl_context self._keepalive_expiry = keepalive_expiry self._http1 = http1 self._http2 = http2
self._network_backend: AsyncNetworkBackend = ( AutoBackend() if network_backend is None else network_backend ) self._connect_lock = AsyncLock() self._connection: AsyncConnectionInterface | None = None self._connect_failed = False
async def handle_async_request(self, request: Request) -> Response: timeouts = request.extensions.get("timeout", {}) sni_hostname = request.extensions.get("sni_hostname", None) timeout = timeouts.get("connect", None)
async with self._connect_lock: if self._connection is None: try: # Connect to the proxy kwargs = { "host": self._proxy_origin.host.decode("ascii"), "port": self._proxy_origin.port, "timeout": timeout, } async with Trace("connect_tcp", logger, request, kwargs) as trace: stream = await self._network_backend.connect_tcp(**kwargs) trace.return_value = stream
# Connect to the remote host using socks5 kwargs = { "stream": stream, "host": self._remote_origin.host.decode("ascii"), "port": self._remote_origin.port, "auth": self._proxy_auth, } async with Trace( "setup_socks5_connection", logger, request, kwargs ) as trace: await _init_socks5_connection(**kwargs) trace.return_value = stream
# Upgrade the stream to SSL if self._remote_origin.scheme == b"https": ssl_context = ( default_ssl_context() if self._ssl_context is None else self._ssl_context ) alpn_protocols = ( ["http/1.1", "h2"] if self._http2 else ["http/1.1"] ) ssl_context.set_alpn_protocols(alpn_protocols)
kwargs = { "ssl_context": ssl_context, "server_hostname": sni_hostname or self._remote_origin.host.decode("ascii"), "timeout": timeout, } async with Trace("start_tls", logger, request, kwargs) as trace: stream = await stream.start_tls(**kwargs) trace.return_value = stream
# Determine if we should be using HTTP/1.1 or HTTP/2 ssl_object = stream.get_extra_info("ssl_object") http2_negotiated = ( ssl_object is not None and ssl_object.selected_alpn_protocol() == "h2" )
# Create the HTTP/1.1 or HTTP/2 connection if http2_negotiated or ( self._http2 and not self._http1 ): # pragma: nocover from .http2 import AsyncHTTP2Connection
self._connection = AsyncHTTP2Connection( origin=self._remote_origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) else: self._connection = AsyncHTTP11Connection( origin=self._remote_origin, stream=stream, keepalive_expiry=self._keepalive_expiry, ) except Exception as exc: self._connect_failed = True raise exc elif not self._connection.is_available(): # pragma: nocover raise ConnectionNotAvailable()
return await self._connection.handle_async_request(request)
def can_handle_request(self, origin: Origin) -> bool: return origin == self._remote_origin
async def aclose(self) -> None: if self._connection is not None: await self._connection.aclose()
def is_available(self) -> bool: if self._connection is None: # pragma: nocover # If HTTP/2 support is enabled, and the resulting connection could # end up as HTTP/2 then we should indicate the connection as being # available to service multiple requests. return ( self._http2 and (self._remote_origin.scheme == b"https" or not self._http1) and not self._connect_failed ) return self._connection.is_available()
def has_expired(self) -> bool: if self._connection is None: # pragma: nocover return self._connect_failed return self._connection.has_expired()
def is_idle(self) -> bool: if self._connection is None: # pragma: nocover return self._connect_failed return self._connection.is_idle()
def is_closed(self) -> bool: if self._connection is None: # pragma: nocover return self._connect_failed return self._connection.is_closed()
def info(self) -> str: if self._connection is None: # pragma: nocover return "CONNECTION FAILED" if self._connect_failed else "CONNECTING" return self._connection.info()
def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.info()}]>"lib/python3.12/site-packages/asttokens/__init__.pyAdded+24
lib/python3.12/site-packages/asttokens/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/asttokens/__pycache__/astroid_compat.cpython-312.pycAdded
lib/python3.12/site-packages/asttokens/__pycache__/asttokens.cpython-312.pycAdded
lib/python3.12/site-packages/asttokens/__pycache__/line_numbers.cpython-312.pycAdded
lib/python3.12/site-packages/asttokens/__pycache__/mark_tokens.cpython-312.pycAdded
lib/python3.12/site-packages/asttokens/__pycache__/util.cpython-312.pycAdded
lib/python3.12/site-packages/asttokens/__pycache__/version.cpython-312.pycAdded
lib/python3.12/site-packages/asttokens/astroid_compat.pyAdded+18
lib/python3.12/site-packages/asttokens/asttokens.pyAdded+450
lib/python3.12/site-packages/asttokens/line_numbers.pyAdded+74
lib/python3.12/site-packages/asttokens/mark_tokens.pyAdded+469
lib/python3.12/site-packages/asttokens/py.typedAdded
lib/python3.12/site-packages/asttokens/version.pyAdded+1
lib/python3.12/site-packages/h11-0.16.0.dist-info/INSTALLERAdded+1
lib/python3.12/site-packages/h11-0.16.0.dist-info/METADATAAdded+202
lib/python3.12/site-packages/h11-0.16.0.dist-info/RECORDAdded+29
lib/python3.12/site-packages/h11-0.16.0.dist-info/WHEELAdded+5
lib/python3.12/site-packages/h11-0.16.0.dist-info/licenses/LICENSE.txtAdded+22
lib/python3.12/site-packages/h11-0.16.0.dist-info/top_level.txtAdded+1
lib/python3.12/site-packages/httpcore/__init__.pyAdded+141
lib/python3.12/site-packages/httpcore/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/__pycache__/_api.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/__pycache__/_exceptions.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/__pycache__/_models.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/__pycache__/_ssl.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/__pycache__/_synchronization.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/__pycache__/_trace.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/__pycache__/_utils.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/_api.pyAdded+94
lib/python3.12/site-packages/httpcore/_async/__init__.pyAdded+39
lib/python3.12/site-packages/httpcore/_async/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/_async/__pycache__/connection.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/_async/__pycache__/connection_pool.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/_async/__pycache__/http11.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/_async/__pycache__/http2.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/_async/__pycache__/http_proxy.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/_async/__pycache__/interfaces.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/_async/__pycache__/socks_proxy.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/_async/connection.pyAdded+222
lib/python3.12/site-packages/httpcore/_async/connection_pool.pyAdded+420
lib/python3.12/site-packages/httpcore/_async/http11.pyAdded+379
lib/python3.12/site-packages/httpcore/_async/http2.pyAdded+592
lib/python3.12/site-packages/httpcore/_async/http_proxy.pyAdded+367
lib/python3.12/site-packages/httpcore/_async/interfaces.pyAdded+137
lib/python3.12/site-packages/httpcore/_async/socks_proxy.pyAdded+341
lib/python3.12/site-packages/httpcore/_backends/__init__.pyAdded
lib/python3.12/site-packages/httpcore/_backends/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/_backends/__pycache__/anyio.cpython-312.pycAdded
lib/python3.12/site-packages/httpcore/_backends/__pycache__/auto.cpython-312.pycAdded