Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c +0 -0
- .cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c.body +88 -0
- .cache/pip/http-v2/0/4/4/7/c/0447ce2249fdae0f8cf52a43e01f215eacdf7c35d89a248bd4b4ebaa +0 -0
- .cache/pip/http-v2/0/4/4/7/c/0447ce2249fdae0f8cf52a43e01f215eacdf7c35d89a248bd4b4ebaa.body +0 -0
- .cache/pip/http-v2/1/e/b/f/d/1ebfddf16e338050f3c69ee3fb0551055792844fc428979435d11f85.body +3 -0
- .cache/pip/http-v2/2/6/9/6/f/2696f961349c363ba6eaa61f1f16df2705938f26ba64023adb039e90.body +0 -0
- .cache/pip/http-v2/2/7/7/6/0/2776091d74378df9859068b389c0d96d3f76c8668c74613451e22e86 +0 -0
- .cache/pip/http-v2/2/9/5/4/2/2954216e93dc816d61408bd6f0b67c741271fd7cfbf7e39bfb692beb +0 -0
- .cache/pip/http-v2/2/9/5/4/2/2954216e93dc816d61408bd6f0b67c741271fd7cfbf7e39bfb692beb.body +581 -0
- .cache/pip/http-v2/2/b/d/2/a/2bd2afb46be8ef29cc0dd505de4aff907384c53895a0fbbce798558e.body +354 -0
- .cache/pip/http-v2/4/5/2/4/1/45241d61b1606b84c3825a9119b750e7cd16e5fac504d31f79203a8e +0 -0
- .cache/pip/http-v2/4/5/2/4/1/45241d61b1606b84c3825a9119b750e7cd16e5fac504d31f79203a8e.body +84 -0
- .cache/pip/http-v2/4/d/c/8/d/4dc8d567db4bc55c0684404c85a6b4572f87a99306be24cab65fbfae.body +0 -0
- .cache/pip/http-v2/5/9/1/a/0/591a0a7ea47d81cffb332bf5e1460e560ce743822558c6f345314d4b +0 -0
- .cache/pip/http-v2/5/9/1/a/0/591a0a7ea47d81cffb332bf5e1460e560ce743822558c6f345314d4b.body +0 -0
- .cache/pip/http-v2/5/e/c/8/b/5ec8b58bc827caa12672b72c08527dbd1c5456edeea815f1e76cb526 +0 -0
- .cache/pip/http-v2/7/2/8/a/2/728a2f33f382f4dacf08f6df77aad6f3d889f819ba4fa3efad5ec7e4 +0 -0
- .cache/pip/http-v2/7/5/c/7/6/75c76ba3da983fc745a6549a0de110dcd624d42b682204260c21f535 +0 -0
- .cache/pip/http-v2/7/9/2/1/a/7921ac3318a5cdb592026cc26a94f7a2c1e1f7d3a1dc1e3857fd49f1 +0 -0
- .cache/pip/http-v2/7/9/2/1/a/7921ac3318a5cdb592026cc26a94f7a2c1e1f7d3a1dc1e3857fd49f1.body +0 -0
- .cache/pip/http-v2/7/f/0/e/c/7f0ec35e0c3a1faba9aada2b4b15e64482162fc43af0f7193ee83003 +0 -0
- .cache/pip/http-v2/b/1/f/5/d/b1f5dc01896eee598e8915be35e61304ad2b16363d00711f8576642c +0 -0
- .cache/pip/http-v2/b/7/8/c/d/b78cd723a0a817da9a40ee919588e074704b65517e7095f1b98b332b +0 -0
- .cache/pip/http-v2/b/e/5/9/9/be599e435b04e9191df28c1690b91394df11dcc43b78b8097f2cac95 +0 -0
- .cache/pip/http-v2/b/e/5/9/9/be599e435b04e9191df28c1690b91394df11dcc43b78b8097f2cac95.body +0 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11-0.16.0.dist-info/METADATA +202 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11-0.16.0.dist-info/RECORD +17 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11-0.16.0.dist-info/WHEEL +5 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11-0.16.0.dist-info/licenses/LICENSE.txt +22 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11-0.16.0.dist-info/top_level.txt +1 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/__init__.py +62 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_abnf.py +132 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_connection.py +659 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_events.py +369 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_headers.py +282 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_readers.py +250 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_receivebuffer.py +153 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_state.py +365 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_util.py +135 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_version.py +16 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_writers.py +145 -0
- .cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/py.typed +1 -0
- .cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx-0.28.1.dist-info/METADATA +203 -0
- .cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx-0.28.1.dist-info/RECORD +29 -0
- .cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx-0.28.1.dist-info/WHEEL +4 -0
- .cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx-0.28.1.dist-info/entry_points.txt +2 -0
- .cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx-0.28.1.dist-info/licenses/LICENSE.md +12 -0
- .cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx/__init__.py +105 -0
- .cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx/__version__.py +3 -0
- .cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx/_api.py +438 -0
.cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c
ADDED
|
Binary file (1.27 kB). View file
|
|
|
.cache/pip/http-v2/0/2/f/7/a/02f7a3cfa8e6aa881ea9780e7473e44a5ee78388ef2ddf2bbdaf9c4c.body
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: Mako
|
| 3 |
+
Version: 1.3.12
|
| 4 |
+
Summary: A super-fast templating language that borrows the best ideas from the existing templating languages.
|
| 5 |
+
Home-page: https://www.makotemplates.org/
|
| 6 |
+
Author: Mike Bayer
|
| 7 |
+
Author-email: mike@zzzcomputing.com
|
| 8 |
+
License: MIT
|
| 9 |
+
Project-URL: Documentation, https://docs.makotemplates.org
|
| 10 |
+
Project-URL: Issue Tracker, https://github.com/sqlalchemy/mako
|
| 11 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 12 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 13 |
+
Classifier: Environment :: Web Environment
|
| 14 |
+
Classifier: Intended Audience :: Developers
|
| 15 |
+
Classifier: Programming Language :: Python
|
| 16 |
+
Classifier: Programming Language :: Python :: 3
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 22 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 23 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 24 |
+
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
| 25 |
+
Requires-Python: >=3.8
|
| 26 |
+
Description-Content-Type: text/x-rst
|
| 27 |
+
License-File: LICENSE
|
| 28 |
+
Requires-Dist: MarkupSafe>=0.9.2
|
| 29 |
+
Provides-Extra: testing
|
| 30 |
+
Requires-Dist: pytest; extra == "testing"
|
| 31 |
+
Provides-Extra: babel
|
| 32 |
+
Requires-Dist: Babel; extra == "babel"
|
| 33 |
+
Provides-Extra: lingua
|
| 34 |
+
Requires-Dist: lingua; extra == "lingua"
|
| 35 |
+
Dynamic: license-file
|
| 36 |
+
|
| 37 |
+
=========================
|
| 38 |
+
Mako Templates for Python
|
| 39 |
+
=========================
|
| 40 |
+
|
| 41 |
+
Mako is a template library written in Python. It provides a familiar, non-XML
|
| 42 |
+
syntax which compiles into Python modules for maximum performance. Mako's
|
| 43 |
+
syntax and API borrows from the best ideas of many others, including Django
|
| 44 |
+
templates, Cheetah, Myghty, and Genshi. Conceptually, Mako is an embedded
|
| 45 |
+
Python (i.e. Python Server Page) language, which refines the familiar ideas
|
| 46 |
+
of componentized layout and inheritance to produce one of the most
|
| 47 |
+
straightforward and flexible models available, while also maintaining close
|
| 48 |
+
ties to Python calling and scoping semantics.
|
| 49 |
+
|
| 50 |
+
Nutshell
|
| 51 |
+
========
|
| 52 |
+
|
| 53 |
+
::
|
| 54 |
+
|
| 55 |
+
<%inherit file="base.html"/>
|
| 56 |
+
<%
|
| 57 |
+
rows = [[v for v in range(0,10)] for row in range(0,10)]
|
| 58 |
+
%>
|
| 59 |
+
<table>
|
| 60 |
+
% for row in rows:
|
| 61 |
+
${makerow(row)}
|
| 62 |
+
% endfor
|
| 63 |
+
</table>
|
| 64 |
+
|
| 65 |
+
<%def name="makerow(row)">
|
| 66 |
+
<tr>
|
| 67 |
+
% for name in row:
|
| 68 |
+
<td>${name}</td>\
|
| 69 |
+
% endfor
|
| 70 |
+
</tr>
|
| 71 |
+
</%def>
|
| 72 |
+
|
| 73 |
+
Philosophy
|
| 74 |
+
===========
|
| 75 |
+
|
| 76 |
+
Python is a great scripting language. Don't reinvent the wheel...your templates can handle it !
|
| 77 |
+
|
| 78 |
+
Documentation
|
| 79 |
+
==============
|
| 80 |
+
|
| 81 |
+
See documentation for Mako at https://docs.makotemplates.org/en/latest/
|
| 82 |
+
|
| 83 |
+
License
|
| 84 |
+
========
|
| 85 |
+
|
| 86 |
+
Mako is licensed under an MIT-style license (see LICENSE).
|
| 87 |
+
Other incorporated projects may be licensed under different licenses.
|
| 88 |
+
All licenses allow for non-commercial and commercial use.
|
.cache/pip/http-v2/0/4/4/7/c/0447ce2249fdae0f8cf52a43e01f215eacdf7c35d89a248bd4b4ebaa
ADDED
|
Binary file (1.9 kB). View file
|
|
|
.cache/pip/http-v2/0/4/4/7/c/0447ce2249fdae0f8cf52a43e01f215eacdf7c35d89a248bd4b4ebaa.body
ADDED
|
Binary file (21 kB). View file
|
|
|
.cache/pip/http-v2/1/e/b/f/d/1ebfddf16e338050f3c69ee3fb0551055792844fc428979435d11f85.body
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1f55797419e16e7f30cf88ffb3113ce0467f00cfe3f70d5c281730b21769bfc2
|
| 3 |
+
size 35287115
|
.cache/pip/http-v2/2/6/9/6/f/2696f961349c363ba6eaa61f1f16df2705938f26ba64023adb039e90.body
ADDED
|
Binary file (78.5 kB). View file
|
|
|
.cache/pip/http-v2/2/7/7/6/0/2776091d74378df9859068b389c0d96d3f76c8668c74613451e22e86
ADDED
|
Binary file (1.21 kB). View file
|
|
|
.cache/pip/http-v2/2/9/5/4/2/2954216e93dc816d61408bd6f0b67c741271fd7cfbf7e39bfb692beb
ADDED
|
Binary file (1.24 kB). View file
|
|
|
.cache/pip/http-v2/2/9/5/4/2/2954216e93dc816d61408bd6f0b67c741271fd7cfbf7e39bfb692beb.body
ADDED
|
@@ -0,0 +1,581 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: timm
|
| 3 |
+
Version: 1.0.27
|
| 4 |
+
Summary: PyTorch Image Models
|
| 5 |
+
Keywords: pytorch,image-classification
|
| 6 |
+
Author-Email: Ross Wightman <ross@huggingface.co>
|
| 7 |
+
License: Apache-2.0
|
| 8 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 9 |
+
Classifier: Intended Audience :: Education
|
| 10 |
+
Classifier: Intended Audience :: Science/Research
|
| 11 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
| 12 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 13 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 14 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 15 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 17 |
+
Classifier: Topic :: Scientific/Engineering
|
| 18 |
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
| 19 |
+
Classifier: Topic :: Software Development
|
| 20 |
+
Classifier: Topic :: Software Development :: Libraries
|
| 21 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 22 |
+
Project-URL: homepage, https://github.com/huggingface/pytorch-image-models
|
| 23 |
+
Project-URL: documentation, https://huggingface.co/docs/timm/en/index
|
| 24 |
+
Project-URL: repository, https://github.com/huggingface/pytorch-image-models
|
| 25 |
+
Requires-Python: >=3.8
|
| 26 |
+
Requires-Dist: torch
|
| 27 |
+
Requires-Dist: torchvision
|
| 28 |
+
Requires-Dist: pyyaml
|
| 29 |
+
Requires-Dist: huggingface_hub
|
| 30 |
+
Requires-Dist: safetensors
|
| 31 |
+
Description-Content-Type: text/markdown
|
| 32 |
+
|
| 33 |
+
# PyTorch Image Models
|
| 34 |
+
- [What's New](#whats-new)
|
| 35 |
+
- [Introduction](#introduction)
|
| 36 |
+
- [Models](#models)
|
| 37 |
+
- [Features](#features)
|
| 38 |
+
- [Results](#results)
|
| 39 |
+
- [Getting Started (Documentation)](#getting-started-documentation)
|
| 40 |
+
- [Train, Validation, Inference Scripts](#train-validation-inference-scripts)
|
| 41 |
+
- [Awesome PyTorch Resources](#awesome-pytorch-resources)
|
| 42 |
+
- [Licenses](#licenses)
|
| 43 |
+
- [Citing](#citing)
|
| 44 |
+
|
| 45 |
+
## What's New
|
| 46 |
+
## May 8, 2026
|
| 47 |
+
* Release 1.0.27
|
| 48 |
+
|
| 49 |
+
## April 23, 2026
|
| 50 |
+
* Add Gemma4 ViT encoders w/ NaFlex pipeline support (variable aspect/size per image). Thanks [Yonghye Kwon](https://github.com/developer0hye)
|
| 51 |
+
* Support DINOv3 weights in NaFlexVit. Thanks [Yonghye Kwon](https://github.com/developer0hye)
|
| 52 |
+
* Some improvements to Muon fallback (AdamW/NadamW) lr behavior
|
| 53 |
+
|
| 54 |
+
## March 23, 2026
|
| 55 |
+
* Improve pickle checkpoint handling security. Default all loading to `weights_only=True`, add safe_global for ArgParse.
|
| 56 |
+
* Improve attention mask handling for core ViT/EVA models & layers. Resolve bool masks, pass `is_causal` through for SSL tasks.
|
| 57 |
+
* Fix class & register token uses with ViT and no pos embed enabled.
|
| 58 |
+
* Add Patch Representation Refinement (PRR) as a pooling option in ViT. Thanks Sina (https://github.com/sinahmr).
|
| 59 |
+
* Improve consistency of output projection / MLP dimensions for attention pooling layers.
|
| 60 |
+
* Hiera model F.SDPA optimization to allow Flash Attention kernel use.
|
| 61 |
+
* Caution added to SGDP optimizer.
|
| 62 |
+
* Release 1.0.26. First maintenance release since my departure from Hugging Face.
|
| 63 |
+
|
| 64 |
+
## Feb 23, 2026
|
| 65 |
+
* Add token distillation training support to distillation task wrappers
|
| 66 |
+
* Remove some torch.jit usage in prep for official deprecation
|
| 67 |
+
* Caution added to AdamP optimizer
|
| 68 |
+
* Call reset_parameters() even if meta-device init so that buffers get init w/ hacks like init_empty_weights
|
| 69 |
+
* Tweak Muon optimizer to work with DTensor/FSDP2 (clamp_ instead of clamp_min_, alternate NS branch for DTensor)
|
| 70 |
+
* Release 1.0.25
|
| 71 |
+
|
| 72 |
+
## Jan 21, 2026
|
| 73 |
+
* **Compat Break**: Fix oversight w/ QKV vs MLP bias in `ParallelScalingBlock` (& `DiffParallelScalingBlock`)
|
| 74 |
+
* Does not impact any trained `timm` models but could impact downstream use.
|
| 75 |
+
|
| 76 |
+
## Jan 5 & 6, 2026
|
| 77 |
+
* Release 1.0.24
|
| 78 |
+
* Add new benchmark result csv files for inference timing on all models w/ RTX Pro 6000, 5090, and 4090 cards w/ PyTorch 2.9.1
|
| 79 |
+
* Fix moved module error in deprecated timm.models.layers import path that impacts legacy imports
|
| 80 |
+
* Release 1.0.23
|
| 81 |
+
|
| 82 |
+
## Dec 30, 2025
|
| 83 |
+
* Add better NAdaMuon trained `dpwee`, `dwee`, `dlittle` (differential) ViTs with a small boost over previous runs
|
| 84 |
+
* https://huggingface.co/timm/vit_dlittle_patch16_reg1_gap_256.sbb_nadamuon_in1k (83.24% top-1)
|
| 85 |
+
* https://huggingface.co/timm/vit_dwee_patch16_reg1_gap_256.sbb_nadamuon_in1k (81.80% top-1)
|
| 86 |
+
* https://huggingface.co/timm/vit_dpwee_patch16_reg1_gap_256.sbb_nadamuon_in1k (81.67% top-1)
|
| 87 |
+
* Add a ~21M param `timm` variant of the CSATv2 model at 512x512 & 640x640
|
| 88 |
+
* https://huggingface.co/timm/csatv2_21m.sw_r640_in1k (83.13% top-1)
|
| 89 |
+
* https://huggingface.co/timm/csatv2_21m.sw_r512_in1k (82.58% top-1)
|
| 90 |
+
* Factor non-persistent param init out of `__init__` into a common method that can be externally called via `init_non_persistent_buffers()` after meta-device init.
|
| 91 |
+
|
| 92 |
+
## Dec 12, 2025
|
| 93 |
+
* Add CSATV2 model (thanks https://github.com/gusdlf93) -- a lightweight but high res model with DCT stem & spatial attention. https://huggingface.co/Hyunil/CSATv2
|
| 94 |
+
* Add AdaMuon and NAdaMuon optimizer support to existing `timm` Muon impl. Appears more competitive vs AdamW with familiar hparams for image tasks.
|
| 95 |
+
* End of year PR cleanup, merge aspects of several long open PR
|
| 96 |
+
* Merge differential attention (`DiffAttention`), add corresponding `DiffParallelScalingBlock` (for ViT), train some wee vits
|
| 97 |
+
* https://huggingface.co/timm/vit_dwee_patch16_reg1_gap_256.sbb_in1k
|
| 98 |
+
* https://huggingface.co/timm/vit_dpwee_patch16_reg1_gap_256.sbb_in1k
|
| 99 |
+
* Add a few pooling modules, `LsePlus` and `SimPool`
|
| 100 |
+
* Cleanup, optimize `DropBlock2d` (also add support to ByobNet based models)
|
| 101 |
+
* Bump unit tests to PyTorch 2.9.1 + Python 3.13 on upper end, lower still PyTorch 1.13 + Python 3.10
|
| 102 |
+
|
| 103 |
+
## Dec 1, 2025
|
| 104 |
+
* Add lightweight task abstraction, add logits and feature distillation support to train script via new tasks.
|
| 105 |
+
* Remove old APEX AMP support
|
| 106 |
+
|
| 107 |
+
## Nov 4, 2025
|
| 108 |
+
* Fix LayerScale / LayerScale2d init bug (init values ignored), introduced in 1.0.21. Thanks https://github.com/Ilya-Fradlin
|
| 109 |
+
* Release 1.0.22
|
| 110 |
+
|
| 111 |
+
## Oct 31, 2025 🎃
|
| 112 |
+
* Update imagenet & OOD variant result csv files to include a few new models and verify correctness over several torch & timm versions
|
| 113 |
+
* EfficientNet-X and EfficientNet-H B5 model weights added as part of a hparam search for AdamW vs Muon (still iterating on Muon runs)
|
| 114 |
+
|
| 115 |
+
## Oct 16-20, 2025
|
| 116 |
+
* Add an impl of the Muon optimizer (based on https://github.com/KellerJordan/Muon) with customizations
|
| 117 |
+
* extra flexibility and improved handling for conv weights and fallbacks for weight shapes not suited for orthogonalization
|
| 118 |
+
* small speedup for NS iterations by reducing allocs and using fused (b)add(b)mm ops
|
| 119 |
+
* by default uses AdamW (or NAdamW if `nesterov=True`) updates if muon not suitable for parameter shape (or excluded via param group flag)
|
| 120 |
+
* like torch impl, select from several LR scale adjustment fns via `adjust_lr_fn`
|
| 121 |
+
* select from several NS coefficient presets or specify your own via `ns_coefficients`
|
| 122 |
+
* First 2 steps of 'meta' device model initialization supported
|
| 123 |
+
* Fix several ops that were breaking creation under 'meta' device context
|
| 124 |
+
* Add device & dtype factory kwarg support to all models and modules (anything inherting from nn.Module) in `timm`
|
| 125 |
+
* License fields added to pretrained cfgs in code
|
| 126 |
+
* Release 1.0.21
|
| 127 |
+
|
| 128 |
+
## Sept 21, 2025
|
| 129 |
+
* Remap DINOv3 ViT weight tags from `lvd_1689m` -> `lvd1689m` to match (same for `sat_493m` -> `sat493m`)
|
| 130 |
+
* Release 1.0.20
|
| 131 |
+
|
| 132 |
+
## Sept 17, 2025
|
| 133 |
+
* DINOv3 (https://arxiv.org/abs/2508.10104) ConvNeXt and ViT models added. ConvNeXt models were mapped to existing `timm` model. ViT support done via the EVA base model w/ a new `RotaryEmbeddingDinoV3` to match the DINOv3 specific RoPE impl
|
| 134 |
+
* HuggingFace Hub: https://huggingface.co/collections/timm/timm-dinov3-68cb08bb0bee365973d52a4d
|
| 135 |
+
* MobileCLIP-2 (https://arxiv.org/abs/2508.20691) vision encoders. New MCI3/MCI4 FastViT variants added and weights mapped to existing FastViT and B, L/14 ViTs.
|
| 136 |
+
* MetaCLIP-2 Worldwide (https://arxiv.org/abs/2507.22062) ViT encoder weights added.
|
| 137 |
+
* SigLIP-2 (https://arxiv.org/abs/2502.14786) NaFlex ViT encoder weights added via timm NaFlexViT model.
|
| 138 |
+
* Misc fixes and contributions
|
| 139 |
+
|
| 140 |
+
## July 23, 2025
|
| 141 |
+
* Add `set_input_size()` method to EVA models, used by OpenCLIP 3.0.0 to allow resizing for timm based encoder models.
|
| 142 |
+
* Release 1.0.18, needed for PE-Core S & T models in OpenCLIP 3.0.0
|
| 143 |
+
* Fix small typing issue that broke Python 3.9 compat. 1.0.19 patch release.
|
| 144 |
+
|
| 145 |
+
## July 21, 2025
|
| 146 |
+
* ROPE support added to NaFlexViT. All models covered by the EVA base (`eva.py`) including EVA, EVA02, Meta PE ViT, `timm` SBB ViT w/ ROPE, and Naver ROPE-ViT can be now loaded in NaFlexViT when `use_naflex=True` passed at model creation time
|
| 147 |
+
* More Meta PE ViT encoders added, including small/tiny variants, lang variants w/ tiling, and more spatial variants.
|
| 148 |
+
* PatchDropout fixed with NaFlexViT and also w/ EVA models (regression after adding Naver ROPE-ViT)
|
| 149 |
+
* Fix XY order with grid_indexing='xy', impacted non-square image use in 'xy' mode (only ROPE-ViT and PE impacted).
|
| 150 |
+
|
| 151 |
+
## July 7, 2025
|
| 152 |
+
* MobileNet-v5 backbone tweaks for improved Google Gemma 3n behaviour (to pair with updated official weights)
|
| 153 |
+
* Add stem bias (zero'd in updated weights, compat break with old weights)
|
| 154 |
+
* GELU -> GELU (tanh approx). A minor change to be closer to JAX
|
| 155 |
+
* Add two arguments to layer-decay support, a min scale clamp and 'no optimization' scale threshold
|
| 156 |
+
* Add 'Fp32' LayerNorm, RMSNorm, SimpleNorm variants that can be enabled to force computation of norm in float32
|
| 157 |
+
* Some typing, argument cleanup for norm, norm+act layers done with above
|
| 158 |
+
* Support Naver ROPE-ViT (https://github.com/naver-ai/rope-vit) in `eva.py`, add RotaryEmbeddingMixed module for mixed mode, weights on HuggingFace Hub
|
| 159 |
+
|
| 160 |
+
|model |img_size|top1 |top5 |param_count|
|
| 161 |
+
|--------------------------------------------------|--------|------|------|-----------|
|
| 162 |
+
|vit_large_patch16_rope_mixed_ape_224.naver_in1k |224 |84.84 |97.122|304.4 |
|
| 163 |
+
|vit_large_patch16_rope_mixed_224.naver_in1k |224 |84.828|97.116|304.2 |
|
| 164 |
+
|vit_large_patch16_rope_ape_224.naver_in1k |224 |84.65 |97.154|304.37 |
|
| 165 |
+
|vit_large_patch16_rope_224.naver_in1k |224 |84.648|97.122|304.17 |
|
| 166 |
+
|vit_base_patch16_rope_mixed_ape_224.naver_in1k |224 |83.894|96.754|86.59 |
|
| 167 |
+
|vit_base_patch16_rope_mixed_224.naver_in1k |224 |83.804|96.712|86.44 |
|
| 168 |
+
|vit_base_patch16_rope_ape_224.naver_in1k |224 |83.782|96.61 |86.59 |
|
| 169 |
+
|vit_base_patch16_rope_224.naver_in1k |224 |83.718|96.672|86.43 |
|
| 170 |
+
|vit_small_patch16_rope_224.naver_in1k |224 |81.23 |95.022|21.98 |
|
| 171 |
+
|vit_small_patch16_rope_mixed_224.naver_in1k |224 |81.216|95.022|21.99 |
|
| 172 |
+
|vit_small_patch16_rope_ape_224.naver_in1k |224 |81.004|95.016|22.06 |
|
| 173 |
+
|vit_small_patch16_rope_mixed_ape_224.naver_in1k |224 |80.986|94.976|22.06 |
|
| 174 |
+
* Some cleanup of ROPE modules, helpers, and FX tracing leaf registration
|
| 175 |
+
* Preparing version 1.0.17 release
|
| 176 |
+
|
| 177 |
+
## June 26, 2025
|
| 178 |
+
* MobileNetV5 backbone (w/ encoder only variant) for [Gemma 3n](https://ai.google.dev/gemma/docs/gemma-3n#parameters) image encoder
|
| 179 |
+
* Version 1.0.16 released
|
| 180 |
+
|
| 181 |
+
## June 23, 2025
|
| 182 |
+
* Add F.grid_sample based 2D and factorized pos embed resize to NaFlexViT. Faster when lots of different sizes (based on example by https://github.com/stas-sl).
|
| 183 |
+
* Further speed up patch embed resample by replacing vmap with matmul (based on snippet by https://github.com/stas-sl).
|
| 184 |
+
* Add 3 initial native aspect NaFlexViT checkpoints created while testing, ImageNet-1k and 3 different pos embed configs w/ same hparams.
|
| 185 |
+
|
| 186 |
+
| Model | Top-1 Acc | Top-5 Acc | Params (M) | Eval Seq Len |
|
| 187 |
+
|:---|:---:|:---:|:---:|:---:|
|
| 188 |
+
| [naflexvit_base_patch16_par_gap.e300_s576_in1k](https://hf.co/timm/naflexvit_base_patch16_par_gap.e300_s576_in1k) | 83.67 | 96.45 | 86.63 | 576 |
|
| 189 |
+
| [naflexvit_base_patch16_parfac_gap.e300_s576_in1k](https://hf.co/timm/naflexvit_base_patch16_parfac_gap.e300_s576_in1k) | 83.63 | 96.41 | 86.46 | 576 |
|
| 190 |
+
| [naflexvit_base_patch16_gap.e300_s576_in1k](https://hf.co/timm/naflexvit_base_patch16_gap.e300_s576_in1k) | 83.50 | 96.46 | 86.63 | 576 |
|
| 191 |
+
* Support gradient checkpointing for `forward_intermediates` and fix some checkpointing bugs. Thanks https://github.com/brianhou0208
|
| 192 |
+
* Add 'corrected weight decay' (https://arxiv.org/abs/2506.02285) as option to AdamW (legacy), Adopt, Kron, Adafactor (BV), Lamb, LaProp, Lion, NadamW, RmsPropTF, SGDW optimizers
|
| 193 |
+
* Switch PE (perception encoder) ViT models to use native timm weights instead of remapping on the fly
|
| 194 |
+
* Fix cuda stream bug in prefetch loader
|
| 195 |
+
|
| 196 |
+
## June 5, 2025
|
| 197 |
+
* Initial NaFlexVit model code. NaFlexVit is a Vision Transformer with:
|
| 198 |
+
1. Encapsulated embedding and position encoding in a single module
|
| 199 |
+
2. Support for nn.Linear patch embedding on pre-patchified (dictionary) inputs
|
| 200 |
+
3. Support for NaFlex variable aspect, variable resolution (SigLip-2: https://arxiv.org/abs/2502.14786)
|
| 201 |
+
4. Support for FlexiViT variable patch size (https://arxiv.org/abs/2212.08013)
|
| 202 |
+
5. Support for NaViT fractional/factorized position embedding (https://arxiv.org/abs/2307.06304)
|
| 203 |
+
* Existing vit models in `vision_transformer.py` can be loaded into the NaFlexVit model by adding the `use_naflex=True` flag to `create_model`
|
| 204 |
+
* Some native weights coming soon
|
| 205 |
+
* A full NaFlex data pipeline is available that allows training / fine-tuning / evaluating with variable aspect / size images
|
| 206 |
+
* To enable in `train.py` and `validate.py` add the `--naflex-loader` arg, must be used with a NaFlexVit
|
| 207 |
+
* To evaluate an existing (classic) ViT loaded in NaFlexVit model w/ NaFlex data pipe:
|
| 208 |
+
* `python validate.py /imagenet --amp -j 8 --model vit_base_patch16_224 --model-kwargs use_naflex=True --naflex-loader --naflex-max-seq-len 256`
|
| 209 |
+
* The training has some extra args features worth noting
|
| 210 |
+
* The `--naflex-train-seq-lens'` argument specifies which sequence lengths to randomly pick from per batch during training
|
| 211 |
+
* The `--naflex-max-seq-len` argument sets the target sequence length for validation
|
| 212 |
+
* Adding `--model-kwargs enable_patch_interpolator=True --naflex-patch-sizes 12 16 24` will enable random patch size selection per-batch w/ interpolation
|
| 213 |
+
* The `--naflex-loss-scale` arg changes loss scaling mode per batch relative to the batch size, `timm` NaFlex loading changes the batch size for each seq len
|
| 214 |
+
|
| 215 |
+
## May 28, 2025
|
| 216 |
+
* Add a number of small/fast models thanks to https://github.com/brianhou0208
|
| 217 |
+
* SwiftFormer - [(ICCV2023) SwiftFormer: Efficient Additive Attention for Transformer-based Real-time Mobile Vision Applications](https://github.com/Amshaker/SwiftFormer)
|
| 218 |
+
* FasterNet - [(CVPR2023) Run, Don’t Walk: Chasing Higher FLOPS for Faster Neural Networks](https://github.com/JierunChen/FasterNet)
|
| 219 |
+
* SHViT - [(CVPR2024) SHViT: Single-Head Vision Transformer with Memory Efficient](https://github.com/ysj9909/SHViT)
|
| 220 |
+
* StarNet - [(CVPR2024) Rewrite the Stars](https://github.com/ma-xu/Rewrite-the-Stars)
|
| 221 |
+
* GhostNet-V3 [GhostNetV3: Exploring the Training Strategies for Compact Models](https://github.com/huawei-noah/Efficient-AI-Backbones/tree/master/ghostnetv3_pytorch)
|
| 222 |
+
* Update EVA ViT (closest match) to support Perception Encoder models (https://arxiv.org/abs/2504.13181) from Meta, loading Hub weights but I still need to push dedicated `timm` weights
|
| 223 |
+
* Add some flexibility to ROPE impl
|
| 224 |
+
* Big increase in number of models supporting `forward_intermediates()` and some additional fixes thanks to https://github.com/brianhou0208
|
| 225 |
+
* DaViT, EdgeNeXt, EfficientFormerV2, EfficientViT(MIT), EfficientViT(MSRA), FocalNet, GCViT, HGNet /V2, InceptionNeXt, Inception-V4, MambaOut, MetaFormer, NesT, Next-ViT, PiT, PVT V2, RepGhostNet, RepViT, ResNetV2, ReXNet, TinyViT, TResNet, VoV
|
| 226 |
+
* TNT model updated w/ new weights `forward_intermediates()` thanks to https://github.com/brianhou0208
|
| 227 |
+
* Add `local-dir:` pretrained schema, can use `local-dir:/path/to/model/folder` for model name to source model / pretrained cfg & weights Hugging Face Hub models (config.json + weights file) from a local folder.
|
| 228 |
+
* Fixes, improvements for onnx export
|
| 229 |
+
|
| 230 |
+
## Feb 21, 2025
|
| 231 |
+
* SigLIP 2 ViT image encoders added (https://huggingface.co/collections/timm/siglip-2-67b8e72ba08b09dd97aecaf9)
|
| 232 |
+
* Variable resolution / aspect NaFlex versions are a WIP
|
| 233 |
+
* Add 'SO150M2' ViT weights trained with SBB recipes, great results, better for ImageNet than previous attempt w/ less training.
|
| 234 |
+
* `vit_so150m2_patch16_reg1_gap_448.sbb_e200_in12k_ft_in1k` - 88.1% top-1
|
| 235 |
+
* `vit_so150m2_patch16_reg1_gap_384.sbb_e200_in12k_ft_in1k` - 87.9% top-1
|
| 236 |
+
* `vit_so150m2_patch16_reg1_gap_256.sbb_e200_in12k_ft_in1k` - 87.3% top-1
|
| 237 |
+
* `vit_so150m2_patch16_reg4_gap_256.sbb_e200_in12k`
|
| 238 |
+
* Updated InternViT-300M '2.5' weights
|
| 239 |
+
* Release 1.0.15
|
| 240 |
+
|
| 241 |
+
## Feb 1, 2025
|
| 242 |
+
* FYI PyTorch 2.6 & Python 3.13 are tested and working w/ current main and released version of `timm`
|
| 243 |
+
|
| 244 |
+
## Jan 27, 2025
|
| 245 |
+
* Add Kron Optimizer (PSGD w/ Kronecker-factored preconditioner)
|
| 246 |
+
* Code from https://github.com/evanatyourservice/kron_torch
|
| 247 |
+
* See also https://sites.google.com/site/lixilinx/home/psgd
|
| 248 |
+
|
| 249 |
+
## Jan 19, 2025
|
| 250 |
+
* Fix loading of LeViT safetensor weights, remove conversion code which should have been deactivated
|
| 251 |
+
* Add 'SO150M' ViT weights trained with SBB recipes, decent results, but not optimal shape for ImageNet-12k/1k pretrain/ft
|
| 252 |
+
* `vit_so150m_patch16_reg4_gap_256.sbb_e250_in12k_ft_in1k` - 86.7% top-1
|
| 253 |
+
* `vit_so150m_patch16_reg4_gap_384.sbb_e250_in12k_ft_in1k` - 87.4% top-1
|
| 254 |
+
* `vit_so150m_patch16_reg4_gap_256.sbb_e250_in12k`
|
| 255 |
+
* Misc typing, typo, etc. cleanup
|
| 256 |
+
* 1.0.14 release to get above LeViT fix out
|
| 257 |
+
|
| 258 |
+
## Jan 9, 2025
|
| 259 |
+
* Add support to train and validate in pure `bfloat16` or `float16`
|
| 260 |
+
* `wandb` project name arg added by https://github.com/caojiaolong, use arg.experiment for name
|
| 261 |
+
* Fix old issue w/ checkpoint saving not working on filesystem w/o hard-link support (e.g. FUSE fs mounts)
|
| 262 |
+
* 1.0.13 release
|
| 263 |
+
|
| 264 |
+
## Jan 6, 2025
|
| 265 |
+
* Add `torch.utils.checkpoint.checkpoint()` wrapper in `timm.models` that defaults `use_reentrant=False`, unless `TIMM_REENTRANT_CKPT=1` is set in env.
|
| 266 |
+
|
| 267 |
+
## Dec 31, 2024
|
| 268 |
+
* `convnext_nano` 384x384 ImageNet-12k pretrain & fine-tune. https://huggingface.co/models?search=convnext_nano%20r384
|
| 269 |
+
* Add AIM-v2 encoders from https://github.com/apple/ml-aim, see on Hub: https://huggingface.co/models?search=timm%20aimv2
|
| 270 |
+
* Add PaliGemma2 encoders from https://github.com/google-research/big_vision to existing PaliGemma, see on Hub: https://huggingface.co/models?search=timm%20pali2
|
| 271 |
+
* Add missing L/14 DFN2B 39B CLIP ViT, `vit_large_patch14_clip_224.dfn2b_s39b`
|
| 272 |
+
* Fix existing `RmsNorm` layer & fn to match standard formulation, use PT 2.5 impl when possible. Move old impl to `SimpleNorm` layer, it's LN w/o centering or bias. There were only two `timm` models using it, and they have been updated.
|
| 273 |
+
* Allow override of `cache_dir` arg for model creation
|
| 274 |
+
* Pass through `trust_remote_code` for HF datasets wrapper
|
| 275 |
+
* `inception_next_atto` model added by creator
|
| 276 |
+
* Adan optimizer caution, and Lamb decoupled weight decay options
|
| 277 |
+
* Some feature_info metadata fixed by https://github.com/brianhou0208
|
| 278 |
+
* All OpenCLIP and JAX (CLIP, SigLIP, Pali, etc) model weights that used load time remapping were given their own HF Hub instances so that they work with `hf-hub:` based loading, and thus will work with new Transformers `TimmWrapperModel`
|
| 279 |
+
|
| 280 |
+
## Introduction
|
| 281 |
+
|
| 282 |
+
Py**T**orch **Im**age **M**odels (`timm`) is a collection of image models, layers, utilities, optimizers, schedulers, data-loaders / augmentations, and reference training / validation scripts that aim to pull together a wide variety of SOTA models with ability to reproduce ImageNet training results.
|
| 283 |
+
|
| 284 |
+
The work of many others is present here. I've tried to make sure all source material is acknowledged via links to github, arxiv papers, etc in the README, documentation, and code docstrings. Please let me know if I missed anything.
|
| 285 |
+
|
| 286 |
+
## Features
|
| 287 |
+
|
| 288 |
+
### Models
|
| 289 |
+
|
| 290 |
+
All model architecture families include variants with pretrained weights. There are specific model variants without any weights, it is NOT a bug. Help training new or better weights is always appreciated.
|
| 291 |
+
|
| 292 |
+
* Aggregating Nested Transformers - https://arxiv.org/abs/2105.12723
|
| 293 |
+
* BEiT - https://arxiv.org/abs/2106.08254
|
| 294 |
+
* BEiT-V2 - https://arxiv.org/abs/2208.06366
|
| 295 |
+
* BEiT3 - https://arxiv.org/abs/2208.10442
|
| 296 |
+
* Big Transfer ResNetV2 (BiT) - https://arxiv.org/abs/1912.11370
|
| 297 |
+
* Bottleneck Transformers - https://arxiv.org/abs/2101.11605
|
| 298 |
+
* CaiT (Class-Attention in Image Transformers) - https://arxiv.org/abs/2103.17239
|
| 299 |
+
* CoaT (Co-Scale Conv-Attentional Image Transformers) - https://arxiv.org/abs/2104.06399
|
| 300 |
+
* CoAtNet (Convolution and Attention) - https://arxiv.org/abs/2106.04803
|
| 301 |
+
* ConvNeXt - https://arxiv.org/abs/2201.03545
|
| 302 |
+
* ConvNeXt-V2 - http://arxiv.org/abs/2301.00808
|
| 303 |
+
* ConViT (Soft Convolutional Inductive Biases Vision Transformers)- https://arxiv.org/abs/2103.10697
|
| 304 |
+
* CspNet (Cross-Stage Partial Networks) - https://arxiv.org/abs/1911.11929
|
| 305 |
+
* DeiT - https://arxiv.org/abs/2012.12877
|
| 306 |
+
* DeiT-III - https://arxiv.org/pdf/2204.07118.pdf
|
| 307 |
+
* DenseNet - https://arxiv.org/abs/1608.06993
|
| 308 |
+
* DLA - https://arxiv.org/abs/1707.06484
|
| 309 |
+
* DPN (Dual-Path Network) - https://arxiv.org/abs/1707.01629
|
| 310 |
+
* EdgeNeXt - https://arxiv.org/abs/2206.10589
|
| 311 |
+
* EfficientFormer - https://arxiv.org/abs/2206.01191
|
| 312 |
+
* EfficientFormer-V2 - https://arxiv.org/abs/2212.08059
|
| 313 |
+
* EfficientNet (MBConvNet Family)
|
| 314 |
+
* EfficientNet NoisyStudent (B0-B7, L2) - https://arxiv.org/abs/1911.04252
|
| 315 |
+
* EfficientNet AdvProp (B0-B8) - https://arxiv.org/abs/1911.09665
|
| 316 |
+
* EfficientNet (B0-B7) - https://arxiv.org/abs/1905.11946
|
| 317 |
+
* EfficientNet-EdgeTPU (S, M, L) - https://ai.googleblog.com/2019/08/efficientnet-edgetpu-creating.html
|
| 318 |
+
* EfficientNet V2 - https://arxiv.org/abs/2104.00298
|
| 319 |
+
* FBNet-C - https://arxiv.org/abs/1812.03443
|
| 320 |
+
* MixNet - https://arxiv.org/abs/1907.09595
|
| 321 |
+
* MNASNet B1, A1 (Squeeze-Excite), and Small - https://arxiv.org/abs/1807.11626
|
| 322 |
+
* MobileNet-V2 - https://arxiv.org/abs/1801.04381
|
| 323 |
+
* Single-Path NAS - https://arxiv.org/abs/1904.02877
|
| 324 |
+
* TinyNet - https://arxiv.org/abs/2010.14819
|
| 325 |
+
* EfficientViT (MIT) - https://arxiv.org/abs/2205.14756
|
| 326 |
+
* EfficientViT (MSRA) - https://arxiv.org/abs/2305.07027
|
| 327 |
+
* EVA - https://arxiv.org/abs/2211.07636
|
| 328 |
+
* EVA-02 - https://arxiv.org/abs/2303.11331
|
| 329 |
+
* FasterNet - https://arxiv.org/abs/2303.03667
|
| 330 |
+
* FastViT - https://arxiv.org/abs/2303.14189
|
| 331 |
+
* FlexiViT - https://arxiv.org/abs/2212.08013
|
| 332 |
+
* FocalNet (Focal Modulation Networks) - https://arxiv.org/abs/2203.11926
|
| 333 |
+
* GCViT (Global Context Vision Transformer) - https://arxiv.org/abs/2206.09959
|
| 334 |
+
* GhostNet - https://arxiv.org/abs/1911.11907
|
| 335 |
+
* GhostNet-V2 - https://arxiv.org/abs/2211.12905
|
| 336 |
+
* GhostNet-V3 - https://arxiv.org/abs/2404.11202
|
| 337 |
+
* gMLP - https://arxiv.org/abs/2105.08050
|
| 338 |
+
* GPU-Efficient Networks - https://arxiv.org/abs/2006.14090
|
| 339 |
+
* Halo Nets - https://arxiv.org/abs/2103.12731
|
| 340 |
+
* HGNet / HGNet-V2 - TBD
|
| 341 |
+
* HRNet - https://arxiv.org/abs/1908.07919
|
| 342 |
+
* InceptionNeXt - https://arxiv.org/abs/2303.16900
|
| 343 |
+
* Inception-V3 - https://arxiv.org/abs/1512.00567
|
| 344 |
+
* Inception-ResNet-V2 and Inception-V4 - https://arxiv.org/abs/1602.07261
|
| 345 |
+
* Lambda Networks - https://arxiv.org/abs/2102.08602
|
| 346 |
+
* LeViT (Vision Transformer in ConvNet's Clothing) - https://arxiv.org/abs/2104.01136
|
| 347 |
+
* MambaOut - https://arxiv.org/abs/2405.07992
|
| 348 |
+
* MaxViT (Multi-Axis Vision Transformer) - https://arxiv.org/abs/2204.01697
|
| 349 |
+
* MetaFormer (PoolFormer-v2, ConvFormer, CAFormer) - https://arxiv.org/abs/2210.13452
|
| 350 |
+
* MLP-Mixer - https://arxiv.org/abs/2105.01601
|
| 351 |
+
* MobileCLIP - https://arxiv.org/abs/2311.17049
|
| 352 |
+
* MobileNet-V3 (MBConvNet w/ Efficient Head) - https://arxiv.org/abs/1905.02244
|
| 353 |
+
* FBNet-V3 - https://arxiv.org/abs/2006.02049
|
| 354 |
+
* HardCoRe-NAS - https://arxiv.org/abs/2102.11646
|
| 355 |
+
* LCNet - https://arxiv.org/abs/2109.15099
|
| 356 |
+
* MobileNetV4 - https://arxiv.org/abs/2404.10518
|
| 357 |
+
* MobileOne - https://arxiv.org/abs/2206.04040
|
| 358 |
+
* MobileViT - https://arxiv.org/abs/2110.02178
|
| 359 |
+
* MobileViT-V2 - https://arxiv.org/abs/2206.02680
|
| 360 |
+
* MViT-V2 (Improved Multiscale Vision Transformer) - https://arxiv.org/abs/2112.01526
|
| 361 |
+
* NASNet-A - https://arxiv.org/abs/1707.07012
|
| 362 |
+
* NesT - https://arxiv.org/abs/2105.12723
|
| 363 |
+
* Next-ViT - https://arxiv.org/abs/2207.05501
|
| 364 |
+
* NFNet-F - https://arxiv.org/abs/2102.06171
|
| 365 |
+
* NF-RegNet / NF-ResNet - https://arxiv.org/abs/2101.08692
|
| 366 |
+
* PE (Perception Encoder) - https://arxiv.org/abs/2504.13181
|
| 367 |
+
* PNasNet - https://arxiv.org/abs/1712.00559
|
| 368 |
+
* PoolFormer (MetaFormer) - https://arxiv.org/abs/2111.11418
|
| 369 |
+
* Pooling-based Vision Transformer (PiT) - https://arxiv.org/abs/2103.16302
|
| 370 |
+
* PVT-V2 (Improved Pyramid Vision Transformer) - https://arxiv.org/abs/2106.13797
|
| 371 |
+
* RDNet (DenseNets Reloaded) - https://arxiv.org/abs/2403.19588
|
| 372 |
+
* RegNet - https://arxiv.org/abs/2003.13678
|
| 373 |
+
* RegNetZ - https://arxiv.org/abs/2103.06877
|
| 374 |
+
* RepVGG - https://arxiv.org/abs/2101.03697
|
| 375 |
+
* RepGhostNet - https://arxiv.org/abs/2211.06088
|
| 376 |
+
* RepViT - https://arxiv.org/abs/2307.09283
|
| 377 |
+
* ResMLP - https://arxiv.org/abs/2105.03404
|
| 378 |
+
* ResNet/ResNeXt
|
| 379 |
+
* ResNet (v1b/v1.5) - https://arxiv.org/abs/1512.03385
|
| 380 |
+
* ResNeXt - https://arxiv.org/abs/1611.05431
|
| 381 |
+
* 'Bag of Tricks' / Gluon C, D, E, S variations - https://arxiv.org/abs/1812.01187
|
| 382 |
+
* Weakly-supervised (WSL) Instagram pretrained / ImageNet tuned ResNeXt101 - https://arxiv.org/abs/1805.00932
|
| 383 |
+
* Semi-supervised (SSL) / Semi-weakly Supervised (SWSL) ResNet/ResNeXts - https://arxiv.org/abs/1905.00546
|
| 384 |
+
* ECA-Net (ECAResNet) - https://arxiv.org/abs/1910.03151v4
|
| 385 |
+
* Squeeze-and-Excitation Networks (SEResNet) - https://arxiv.org/abs/1709.01507
|
| 386 |
+
* ResNet-RS - https://arxiv.org/abs/2103.07579
|
| 387 |
+
* Res2Net - https://arxiv.org/abs/1904.01169
|
| 388 |
+
* ResNeSt - https://arxiv.org/abs/2004.08955
|
| 389 |
+
* ReXNet - https://arxiv.org/abs/2007.00992
|
| 390 |
+
* ROPE-ViT - https://arxiv.org/abs/2403.13298
|
| 391 |
+
* SelecSLS - https://arxiv.org/abs/1907.00837
|
| 392 |
+
* Selective Kernel Networks - https://arxiv.org/abs/1903.06586
|
| 393 |
+
* Sequencer2D - https://arxiv.org/abs/2205.01972
|
| 394 |
+
* SHViT - https://arxiv.org/abs/2401.16456
|
| 395 |
+
* SigLIP (image encoder) - https://arxiv.org/abs/2303.15343
|
| 396 |
+
* SigLIP 2 (image encoder) - https://arxiv.org/abs/2502.14786
|
| 397 |
+
* StarNet - https://arxiv.org/abs/2403.19967
|
| 398 |
+
* SwiftFormer - https://arxiv.org/pdf/2303.15446
|
| 399 |
+
* Swin S3 (AutoFormerV2) - https://arxiv.org/abs/2111.14725
|
| 400 |
+
* Swin Transformer - https://arxiv.org/abs/2103.14030
|
| 401 |
+
* Swin Transformer V2 - https://arxiv.org/abs/2111.09883
|
| 402 |
+
* TinyViT - https://arxiv.org/abs/2207.10666
|
| 403 |
+
* Transformer-iN-Transformer (TNT) - https://arxiv.org/abs/2103.00112
|
| 404 |
+
* TResNet - https://arxiv.org/abs/2003.13630
|
| 405 |
+
* Twins (Spatial Attention in Vision Transformers) - https://arxiv.org/pdf/2104.13840.pdf
|
| 406 |
+
* VGG - https://arxiv.org/abs/1409.1556
|
| 407 |
+
* Visformer - https://arxiv.org/abs/2104.12533
|
| 408 |
+
* Vision Transformer - https://arxiv.org/abs/2010.11929
|
| 409 |
+
* ViTamin - https://arxiv.org/abs/2404.02132
|
| 410 |
+
* VOLO (Vision Outlooker) - https://arxiv.org/abs/2106.13112
|
| 411 |
+
* VovNet V2 and V1 - https://arxiv.org/abs/1911.06667
|
| 412 |
+
* Xception - https://arxiv.org/abs/1610.02357
|
| 413 |
+
* Xception (Modified Aligned, Gluon) - https://arxiv.org/abs/1802.02611
|
| 414 |
+
* Xception (Modified Aligned, TF) - https://arxiv.org/abs/1802.02611
|
| 415 |
+
* XCiT (Cross-Covariance Image Transformers) - https://arxiv.org/abs/2106.09681
|
| 416 |
+
|
| 417 |
+
### Optimizers
|
| 418 |
+
To see full list of optimizers w/ descriptions: `timm.optim.list_optimizers(with_description=True)`
|
| 419 |
+
|
| 420 |
+
Included optimizers available via `timm.optim.create_optimizer_v2` factory method:
|
| 421 |
+
* `adabelief` an implementation of AdaBelief adapted from https://github.com/juntang-zhuang/Adabelief-Optimizer - https://arxiv.org/abs/2010.07468
|
| 422 |
+
* `adafactor` adapted from [FAIRSeq impl](https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py) - https://arxiv.org/abs/1804.04235
|
| 423 |
+
* `adafactorbv` adapted from [Big Vision](https://github.com/google-research/big_vision/blob/main/big_vision/optax.py) - https://arxiv.org/abs/2106.04560
|
| 424 |
+
* `adahessian` by [David Samuel](https://github.com/davda54/ada-hessian) - https://arxiv.org/abs/2006.00719
|
| 425 |
+
* `adamp` and `sgdp` by [Naver ClovAI](https://github.com/clovaai) - https://arxiv.org/abs/2006.08217
|
| 426 |
+
* `adamuon` and `nadamuon` as per https://github.com/Chongjie-Si/AdaMuon - https://arxiv.org/abs/2507.11005
|
| 427 |
+
* `adan` an implementation of Adan adapted from https://github.com/sail-sg/Adan - https://arxiv.org/abs/2208.06677
|
| 428 |
+
* `adopt` ADOPT adapted from https://github.com/iShohei220/adopt - https://arxiv.org/abs/2411.02853
|
| 429 |
+
* `kron` PSGD w/ Kronecker-factored preconditioner from https://github.com/evanatyourservice/kron_torch - https://sites.google.com/site/lixilinx/home/psgd
|
| 430 |
+
* `lamb` an implementation of Lamb and LambC (w/ trust-clipping) cleaned up and modified to support use with XLA - https://arxiv.org/abs/1904.00962
|
| 431 |
+
* `laprop` optimizer from https://github.com/Z-T-WANG/LaProp-Optimizer - https://arxiv.org/abs/2002.04839
|
| 432 |
+
* `lars` an implementation of LARS and LARC (w/ trust-clipping) - https://arxiv.org/abs/1708.03888
|
| 433 |
+
* `lion` and implementation of Lion adapted from https://github.com/google/automl/tree/master/lion - https://arxiv.org/abs/2302.06675
|
| 434 |
+
* `lookahead` adapted from impl by [Liam](https://github.com/alphadl/lookahead.pytorch) - https://arxiv.org/abs/1907.08610
|
| 435 |
+
* `madgrad` an implementation of MADGRAD adapted from https://github.com/facebookresearch/madgrad - https://arxiv.org/abs/2101.11075
|
| 436 |
+
* `mars` MARS optimizer from https://github.com/AGI-Arena/MARS - https://arxiv.org/abs/2411.10438
|
| 437 |
+
* `muon` MUON optimizer from https://github.com/KellerJordan/Muon with numerous additions and improved non-transformer behaviour
|
| 438 |
+
* `nadam` an implementation of Adam w/ Nesterov momentum
|
| 439 |
+
* `nadamw` an implementation of AdamW (Adam w/ decoupled weight-decay) w/ Nesterov momentum. A simplified impl based on https://github.com/mlcommons/algorithmic-efficiency
|
| 440 |
+
* `novograd` by [Masashi Kimura](https://github.com/convergence-lab/novograd) - https://arxiv.org/abs/1905.11286
|
| 441 |
+
* `radam` by [Liyuan Liu](https://github.com/LiyuanLucasLiu/RAdam) - https://arxiv.org/abs/1908.03265
|
| 442 |
+
* `rmsprop_tf` adapted from PyTorch RMSProp by myself. Reproduces much improved Tensorflow RMSProp behaviour
|
| 443 |
+
* `sgdw` and implementation of SGD w/ decoupled weight-decay
|
| 444 |
+
* `fused<name>` optimizers by name with [NVIDIA Apex](https://github.com/NVIDIA/apex/tree/master/apex/optimizers) installed
|
| 445 |
+
* `bnb<name>` optimizers by name with [BitsAndBytes](https://github.com/TimDettmers/bitsandbytes) installed
|
| 446 |
+
* `cadamw`, `clion`, and more 'Cautious' optimizers from https://github.com/kyleliang919/C-Optim - https://arxiv.org/abs/2411.16085
|
| 447 |
+
* `adam`, `adamw`, `rmsprop`, `adadelta`, `adagrad`, and `sgd` pass through to `torch.optim` implementations
|
| 448 |
+
* `c` suffix (eg `adamc`, `nadamc` to implement 'corrected weight decay' in https://arxiv.org/abs/2506.02285)
|
| 449 |
+
|
| 450 |
+
### Augmentations
|
| 451 |
+
* Random Erasing from [Zhun Zhong](https://github.com/zhunzhong07/Random-Erasing/blob/master/transforms.py) - https://arxiv.org/abs/1708.04896)
|
| 452 |
+
* Mixup - https://arxiv.org/abs/1710.09412
|
| 453 |
+
* CutMix - https://arxiv.org/abs/1905.04899
|
| 454 |
+
* AutoAugment (https://arxiv.org/abs/1805.09501) and RandAugment (https://arxiv.org/abs/1909.13719) ImageNet configurations modeled after impl for EfficientNet training (https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py)
|
| 455 |
+
* AugMix w/ JSD loss, JSD w/ clean + augmented mixing support works with AutoAugment and RandAugment as well - https://arxiv.org/abs/1912.02781
|
| 456 |
+
* SplitBachNorm - allows splitting batch norm layers between clean and augmented (auxiliary batch norm) data
|
| 457 |
+
|
| 458 |
+
### Regularization
|
| 459 |
+
* DropPath aka "Stochastic Depth" - https://arxiv.org/abs/1603.09382
|
| 460 |
+
* DropBlock - https://arxiv.org/abs/1810.12890
|
| 461 |
+
* Blur Pooling - https://arxiv.org/abs/1904.11486
|
| 462 |
+
|
| 463 |
+
### Other
|
| 464 |
+
|
| 465 |
+
Several (less common) features that I often utilize in my projects are included. Many of their additions are the reason why I maintain my own set of models, instead of using others' via PIP:
|
| 466 |
+
|
| 467 |
+
* All models have a common default configuration interface and API for
|
| 468 |
+
* accessing/changing the classifier - `get_classifier` and `reset_classifier`
|
| 469 |
+
* doing a forward pass on just the features - `forward_features` (see [documentation](https://huggingface.co/docs/timm/feature_extraction))
|
| 470 |
+
* these makes it easy to write consistent network wrappers that work with any of the models
|
| 471 |
+
* All models support multi-scale feature map extraction (feature pyramids) via create_model (see [documentation](https://huggingface.co/docs/timm/feature_extraction))
|
| 472 |
+
* `create_model(name, features_only=True, out_indices=..., output_stride=...)`
|
| 473 |
+
* `out_indices` creation arg specifies which feature maps to return, these indices are 0 based and generally correspond to the `C(i + 1)` feature level.
|
| 474 |
+
* `output_stride` creation arg controls output stride of the network by using dilated convolutions. Most networks are stride 32 by default. Not all networks support this.
|
| 475 |
+
* feature map channel counts, reduction level (stride) can be queried AFTER model creation via the `.feature_info` member
|
| 476 |
+
* All models have a consistent pretrained weight loader that adapts last linear if necessary, and from 3 to 1 channel input if desired
|
| 477 |
+
* High performance [reference training, validation, and inference scripts](https://huggingface.co/docs/timm/training_script) that work in several process/GPU modes:
|
| 478 |
+
* NVIDIA DDP w/ a single GPU per process, multiple processes with APEX present (AMP mixed-precision optional)
|
| 479 |
+
* PyTorch DistributedDataParallel w/ multi-gpu, single process (AMP disabled as it crashes when enabled)
|
| 480 |
+
* PyTorch w/ single GPU single process (AMP optional)
|
| 481 |
+
* A dynamic global pool implementation that allows selecting from average pooling, max pooling, average + max, or concat([average, max]) at model creation. All global pooling is adaptive average by default and compatible with pretrained weights.
|
| 482 |
+
* A 'Test Time Pool' wrapper that can wrap any of the included models and usually provides improved performance doing inference with input images larger than the training size. Idea adapted from original DPN implementation when I ported (https://github.com/cypw/DPNs)
|
| 483 |
+
* Learning rate schedulers
|
| 484 |
+
* Ideas adopted from
|
| 485 |
+
* [AllenNLP schedulers](https://github.com/allenai/allennlp/tree/master/allennlp/training/learning_rate_schedulers)
|
| 486 |
+
* [FAIRseq lr_scheduler](https://github.com/pytorch/fairseq/tree/master/fairseq/optim/lr_scheduler)
|
| 487 |
+
* SGDR: Stochastic Gradient Descent with Warm Restarts (https://arxiv.org/abs/1608.03983)
|
| 488 |
+
* Schedulers include `step`, `cosine` w/ restarts, `tanh` w/ restarts, `plateau`
|
| 489 |
+
* Space-to-Depth by [mrT23](https://github.com/mrT23/TResNet/blob/master/src/models/tresnet/layers/space_to_depth.py) (https://arxiv.org/abs/1801.04590)
|
| 490 |
+
* Adaptive Gradient Clipping (https://arxiv.org/abs/2102.06171, https://github.com/deepmind/deepmind-research/tree/master/nfnets)
|
| 491 |
+
* An extensive selection of channel and/or spatial attention modules:
|
| 492 |
+
* Bottleneck Transformer - https://arxiv.org/abs/2101.11605
|
| 493 |
+
* CBAM - https://arxiv.org/abs/1807.06521
|
| 494 |
+
* Effective Squeeze-Excitation (ESE) - https://arxiv.org/abs/1911.06667
|
| 495 |
+
* Efficient Channel Attention (ECA) - https://arxiv.org/abs/1910.03151
|
| 496 |
+
* Gather-Excite (GE) - https://arxiv.org/abs/1810.12348
|
| 497 |
+
* Global Context (GC) - https://arxiv.org/abs/1904.11492
|
| 498 |
+
* Halo - https://arxiv.org/abs/2103.12731
|
| 499 |
+
* Involution - https://arxiv.org/abs/2103.06255
|
| 500 |
+
* Lambda Layer - https://arxiv.org/abs/2102.08602
|
| 501 |
+
* Non-Local (NL) - https://arxiv.org/abs/1711.07971
|
| 502 |
+
* Squeeze-and-Excitation (SE) - https://arxiv.org/abs/1709.01507
|
| 503 |
+
* Selective Kernel (SK) - (https://arxiv.org/abs/1903.06586
|
| 504 |
+
* Split (SPLAT) - https://arxiv.org/abs/2004.08955
|
| 505 |
+
* Shifted Window (SWIN) - https://arxiv.org/abs/2103.14030
|
| 506 |
+
|
| 507 |
+
## Results
|
| 508 |
+
|
| 509 |
+
Model validation results can be found in the [results tables](results/README.md)
|
| 510 |
+
|
| 511 |
+
## Getting Started (Documentation)
|
| 512 |
+
|
| 513 |
+
The official documentation can be found at https://huggingface.co/docs/hub/timm. Documentation contributions are welcome.
|
| 514 |
+
|
| 515 |
+
[Getting Started with PyTorch Image Models (timm): A Practitioner’s Guide](https://towardsdatascience.com/getting-started-with-pytorch-image-models-timm-a-practitioners-guide-4e77b4bf9055-2/) by [Chris Hughes](https://github.com/Chris-hughes10) is an extensive blog post covering many aspects of `timm` in detail.
|
| 516 |
+
|
| 517 |
+
[timmdocs](http://timm.fast.ai/) is an alternate set of documentation for `timm`. A big thanks to [Aman Arora](https://github.com/amaarora) for his efforts creating timmdocs.
|
| 518 |
+
|
| 519 |
+
[paperswithcode](https://paperswithcode.com/lib/timm) is a good resource for browsing the models within `timm`.
|
| 520 |
+
|
| 521 |
+
## Train, Validation, Inference Scripts
|
| 522 |
+
|
| 523 |
+
The root folder of the repository contains reference train, validation, and inference scripts that work with the included models and other features of this repository. They are adaptable for other datasets and use cases with a little hacking. See [documentation](https://huggingface.co/docs/timm/training_script).
|
| 524 |
+
|
| 525 |
+
## Awesome PyTorch Resources
|
| 526 |
+
|
| 527 |
+
One of the greatest assets of PyTorch is the community and their contributions. A few of my favourite resources that pair well with the models and components here are listed below.
|
| 528 |
+
|
| 529 |
+
### Object Detection, Instance and Semantic Segmentation
|
| 530 |
+
* Detectron2 - https://github.com/facebookresearch/detectron2
|
| 531 |
+
* Segmentation Models (Semantic) - https://github.com/qubvel/segmentation_models.pytorch
|
| 532 |
+
* EfficientDet (Obj Det, Semantic soon) - https://github.com/rwightman/efficientdet-pytorch
|
| 533 |
+
|
| 534 |
+
### Computer Vision / Image Augmentation
|
| 535 |
+
* Albumentations - https://github.com/albumentations-team/albumentations
|
| 536 |
+
* Kornia - https://github.com/kornia/kornia
|
| 537 |
+
|
| 538 |
+
### Knowledge Distillation
|
| 539 |
+
* RepDistiller - https://github.com/HobbitLong/RepDistiller
|
| 540 |
+
* torchdistill - https://github.com/yoshitomo-matsubara/torchdistill
|
| 541 |
+
|
| 542 |
+
### Metric Learning
|
| 543 |
+
* PyTorch Metric Learning - https://github.com/KevinMusgrave/pytorch-metric-learning
|
| 544 |
+
|
| 545 |
+
### Training / Frameworks
|
| 546 |
+
* fastai - https://github.com/fastai/fastai
|
| 547 |
+
* lightly_train - https://github.com/lightly-ai/lightly-train
|
| 548 |
+
|
| 549 |
+
### Deployment
|
| 550 |
+
* timmx (Export timm models to ONNX, CoreML, LiteRT, TensorRT, and more) - https://github.com/Boulaouaney/timmx
|
| 551 |
+
|
| 552 |
+
## Licenses
|
| 553 |
+
|
| 554 |
+
### Code
|
| 555 |
+
The code here is licensed Apache 2.0. I've taken care to make sure any third party code included or adapted has compatible (permissive) licenses such as MIT, BSD, etc. I've made an effort to avoid any GPL / LGPL conflicts. That said, it is your responsibility to ensure you comply with licenses here and conditions of any dependent licenses. Where applicable, I've linked the sources/references for various components in docstrings. If you think I've missed anything please create an issue.
|
| 556 |
+
|
| 557 |
+
### Pretrained Weights
|
| 558 |
+
So far all of the pretrained weights available here are pretrained on ImageNet with a select few that have some additional pretraining (see extra note below). ImageNet was released for non-commercial research purposes only (https://image-net.org/download). It's not clear what the implications of that are for the use of pretrained weights from that dataset. Any models I have trained with ImageNet are done for research purposes and one should assume that the original dataset license applies to the weights. It's best to seek legal advice if you intend to use the pretrained weights in a commercial product.
|
| 559 |
+
|
| 560 |
+
#### Pretrained on more than ImageNet
|
| 561 |
+
Several weights included or references here were pretrained with proprietary datasets that I do not have access to. These include the Facebook WSL, SSL, SWSL ResNe(Xt) and the Google Noisy Student EfficientNet models. The Facebook models have an explicit non-commercial license (CC-BY-NC 4.0, https://github.com/facebookresearch/semi-supervised-ImageNet1K-models, https://github.com/facebookresearch/WSL-Images). The Google models do not appear to have any restriction beyond the Apache 2.0 license (and ImageNet concerns). In either case, you should contact Facebook or Google with any questions.
|
| 562 |
+
|
| 563 |
+
## Citing
|
| 564 |
+
|
| 565 |
+
### BibTeX
|
| 566 |
+
|
| 567 |
+
```bibtex
|
| 568 |
+
@misc{rw2019timm,
|
| 569 |
+
author = {Ross Wightman},
|
| 570 |
+
title = {PyTorch Image Models},
|
| 571 |
+
year = {2019},
|
| 572 |
+
publisher = {GitHub},
|
| 573 |
+
journal = {GitHub repository},
|
| 574 |
+
doi = {10.5281/zenodo.4414861},
|
| 575 |
+
howpublished = {\url{https://github.com/rwightman/pytorch-image-models}}
|
| 576 |
+
}
|
| 577 |
+
```
|
| 578 |
+
|
| 579 |
+
### Latest DOI
|
| 580 |
+
|
| 581 |
+
[](https://zenodo.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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: optuna
|
| 3 |
+
Version: 4.9.0
|
| 4 |
+
Summary: A hyperparameter optimization framework
|
| 5 |
+
Author: Takuya Akiba
|
| 6 |
+
Project-URL: homepage, https://optuna.org/
|
| 7 |
+
Project-URL: repository, https://github.com/optuna/optuna
|
| 8 |
+
Project-URL: documentation, https://optuna.readthedocs.io
|
| 9 |
+
Project-URL: bugtracker, https://github.com/optuna/optuna/issues
|
| 10 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 11 |
+
Classifier: Intended Audience :: Science/Research
|
| 12 |
+
Classifier: Intended Audience :: Developers
|
| 13 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 14 |
+
Classifier: Programming Language :: Python :: 3
|
| 15 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 21 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 22 |
+
Classifier: Topic :: Scientific/Engineering
|
| 23 |
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
| 24 |
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
| 25 |
+
Classifier: Topic :: Software Development
|
| 26 |
+
Classifier: Topic :: Software Development :: Libraries
|
| 27 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 28 |
+
Requires-Python: >=3.9
|
| 29 |
+
Description-Content-Type: text/markdown
|
| 30 |
+
License-File: LICENSE
|
| 31 |
+
License-File: LICENSE_THIRD_PARTY
|
| 32 |
+
Requires-Dist: alembic>=1.5.0
|
| 33 |
+
Requires-Dist: colorlog
|
| 34 |
+
Requires-Dist: numpy
|
| 35 |
+
Requires-Dist: packaging>=20.0
|
| 36 |
+
Requires-Dist: sqlalchemy>=1.4.2
|
| 37 |
+
Requires-Dist: tqdm
|
| 38 |
+
Requires-Dist: PyYAML
|
| 39 |
+
Provides-Extra: document
|
| 40 |
+
Requires-Dist: ase; extra == "document"
|
| 41 |
+
Requires-Dist: cmaes>=0.12.0; extra == "document"
|
| 42 |
+
Requires-Dist: fvcore; extra == "document"
|
| 43 |
+
Requires-Dist: kaleido!=0.2.1.post1,<0.4; extra == "document"
|
| 44 |
+
Requires-Dist: lightgbm; extra == "document"
|
| 45 |
+
Requires-Dist: matplotlib!=3.6.0; extra == "document"
|
| 46 |
+
Requires-Dist: pandas; extra == "document"
|
| 47 |
+
Requires-Dist: pillow; extra == "document"
|
| 48 |
+
Requires-Dist: plotly>=4.9.0; extra == "document"
|
| 49 |
+
Requires-Dist: scikit-learn; extra == "document"
|
| 50 |
+
Requires-Dist: sphinx; extra == "document"
|
| 51 |
+
Requires-Dist: sphinx-copybutton; extra == "document"
|
| 52 |
+
Requires-Dist: sphinx-gallery; extra == "document"
|
| 53 |
+
Requires-Dist: sphinx-notfound-page; extra == "document"
|
| 54 |
+
Requires-Dist: sphinx_rtd_theme>=1.2.0; extra == "document"
|
| 55 |
+
Requires-Dist: torch; extra == "document"
|
| 56 |
+
Requires-Dist: torchvision; extra == "document"
|
| 57 |
+
Provides-Extra: optional
|
| 58 |
+
Requires-Dist: boto3; extra == "optional"
|
| 59 |
+
Requires-Dist: cmaes>=0.12.0; extra == "optional"
|
| 60 |
+
Requires-Dist: google-cloud-storage; extra == "optional"
|
| 61 |
+
Requires-Dist: matplotlib!=3.6.0; extra == "optional"
|
| 62 |
+
Requires-Dist: pandas; extra == "optional"
|
| 63 |
+
Requires-Dist: plotly>=4.9.0; extra == "optional"
|
| 64 |
+
Requires-Dist: redis; extra == "optional"
|
| 65 |
+
Requires-Dist: scikit-learn>=0.24.2; extra == "optional"
|
| 66 |
+
Requires-Dist: scipy; extra == "optional"
|
| 67 |
+
Requires-Dist: torch; extra == "optional"
|
| 68 |
+
Requires-Dist: greenlet; extra == "optional"
|
| 69 |
+
Requires-Dist: grpcio; extra == "optional"
|
| 70 |
+
Requires-Dist: protobuf>=5.28.1; extra == "optional"
|
| 71 |
+
Dynamic: license-file
|
| 72 |
+
|
| 73 |
+
<div align="center"><img src="https://raw.githubusercontent.com/optuna/optuna/master/docs/image/optuna-logo.png" width="800"/></div>
|
| 74 |
+
|
| 75 |
+
# Optuna: A hyperparameter optimization framework
|
| 76 |
+
|
| 77 |
+
[](https://www.python.org)
|
| 78 |
+
[](https://pypi.python.org/pypi/optuna)
|
| 79 |
+
[](https://anaconda.org/conda-forge/optuna)
|
| 80 |
+
[](https://github.com/optuna/optuna)
|
| 81 |
+
[](https://optuna.readthedocs.io/en/stable/)
|
| 82 |
+
|
| 83 |
+
:link: [**Website**](https://optuna.org/)
|
| 84 |
+
| :page_with_curl: [**Docs**](https://optuna.readthedocs.io/en/stable/)
|
| 85 |
+
| :gear: [**Install Guide**](https://optuna.readthedocs.io/en/stable/installation.html)
|
| 86 |
+
| :pencil: [**Tutorial**](https://optuna.readthedocs.io/en/stable/tutorial/index.html)
|
| 87 |
+
| :bulb: [**Examples**](https://github.com/optuna/optuna-examples)
|
| 88 |
+
| [**Twitter**](https://twitter.com/OptunaAutoML)
|
| 89 |
+
| [**LinkedIn**](https://www.linkedin.com/showcase/optuna/)
|
| 90 |
+
| [**Medium**](https://medium.com/optuna)
|
| 91 |
+
|
| 92 |
+
*Optuna* is an automatic hyperparameter optimization software framework, particularly designed
|
| 93 |
+
for machine learning. It features an imperative, *define-by-run* style user API. Thanks to our
|
| 94 |
+
*define-by-run* API, the code written with Optuna enjoys high modularity, and the user of
|
| 95 |
+
Optuna can dynamically construct the search spaces for the hyperparameters.
|
| 96 |
+
|
| 97 |
+
## :loudspeaker: News
|
| 98 |
+
|
| 99 |
+
<!-- TODO: when you add a new line, please delete the oldest line -->
|
| 100 |
+
* **Mar 16, 2026**: Optuna 4.8.0 is out! Check out [the release note](https://github.com/optuna/optuna/releases/tag/v4.8.0) for details.
|
| 101 |
+
* **Jan 19, 2026**: Optuna 4.7.0 is out! Check out [the release note](https://github.com/optuna/optuna/releases/tag/v4.7.0) for details.
|
| 102 |
+
* **Nov 10, 2025**: A new article [Announcing Optuna 4.6](https://medium.com/optuna/announcing-optuna-4-6-a9e82183ab07) has been published.
|
| 103 |
+
* **Oct 28, 2025**: A new article [AutoSampler: Full Support for Multi-Objective & Constrained Optimization](https://medium.com/optuna/autosampler-full-support-for-multi-objective-constrained-optimization-c1c4fc957ba2) has been published.
|
| 104 |
+
* **Sep 22, 2025**: A new article [[Optuna v4.5] Gaussian Process-Based Sampler (GPSampler) Can Now Perform Constrained Multi-Objective Optimization](https://medium.com/optuna/optuna-v4-5-81e78d8e077a) has been published.
|
| 105 |
+
* **Jun 16, 2025**: Optuna 4.4.0 has been released! Check out [the release blog](https://medium.com/optuna/announcing-optuna-4-4-ece661493126).
|
| 106 |
+
|
| 107 |
+
## :fire: Key Features
|
| 108 |
+
|
| 109 |
+
Optuna has modern functionalities as follows:
|
| 110 |
+
|
| 111 |
+
- [Lightweight, versatile, and platform agnostic architecture](https://optuna.readthedocs.io/en/stable/tutorial/10_key_features/001_first.html)
|
| 112 |
+
- Handle a wide variety of tasks with a simple installation that has few requirements.
|
| 113 |
+
- [Pythonic search spaces](https://optuna.readthedocs.io/en/stable/tutorial/10_key_features/002_configurations.html)
|
| 114 |
+
- Define search spaces using familiar Python syntax including conditionals and loops.
|
| 115 |
+
- [Efficient optimization algorithms](https://optuna.readthedocs.io/en/stable/tutorial/10_key_features/003_efficient_optimization_algorithms.html)
|
| 116 |
+
- Adopt state-of-the-art algorithms for sampling hyperparameters and efficiently pruning unpromising trials.
|
| 117 |
+
- [Easy parallelization](https://optuna.readthedocs.io/en/stable/tutorial/10_key_features/004_distributed.html)
|
| 118 |
+
- Scale studies to tens or hundreds of workers with little or no changes to the code.
|
| 119 |
+
- [Quick visualization](https://optuna.readthedocs.io/en/stable/tutorial/10_key_features/005_visualization.html)
|
| 120 |
+
- Inspect optimization histories from a variety of plotting functions.
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
## Basic Concepts
|
| 124 |
+
|
| 125 |
+
We use the terms *study* and *trial* as follows:
|
| 126 |
+
|
| 127 |
+
- Study: optimization based on an objective function
|
| 128 |
+
- Trial: a single execution of the objective function
|
| 129 |
+
|
| 130 |
+
Please refer to the sample code below. The goal of a *study* is to find out the optimal set of
|
| 131 |
+
hyperparameter values (e.g., `regressor` and `svr_c`) through multiple *trials* (e.g.,
|
| 132 |
+
`n_trials=100`). Optuna is a framework designed for automation and acceleration of
|
| 133 |
+
optimization *studies*.
|
| 134 |
+
|
| 135 |
+
<details open>
|
| 136 |
+
<summary>Sample code with scikit-learn</summary>
|
| 137 |
+
|
| 138 |
+
[](http://colab.research.google.com/github/optuna/optuna-examples/blob/main/quickstart.ipynb)
|
| 139 |
+
|
| 140 |
+
```python
|
| 141 |
+
import optuna
|
| 142 |
+
import sklearn
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# Define an objective function to be minimized.
|
| 146 |
+
def objective(trial):
|
| 147 |
+
|
| 148 |
+
# Invoke suggest methods of a Trial object to generate hyperparameters.
|
| 149 |
+
regressor_name = trial.suggest_categorical("regressor", ["SVR", "RandomForest"])
|
| 150 |
+
if regressor_name == "SVR":
|
| 151 |
+
svr_c = trial.suggest_float("svr_c", 1e-10, 1e10, log=True)
|
| 152 |
+
regressor_obj = sklearn.svm.SVR(C=svr_c)
|
| 153 |
+
else:
|
| 154 |
+
rf_max_depth = trial.suggest_int("rf_max_depth", 2, 32)
|
| 155 |
+
regressor_obj = sklearn.ensemble.RandomForestRegressor(max_depth=rf_max_depth)
|
| 156 |
+
|
| 157 |
+
X, y = sklearn.datasets.fetch_california_housing(return_X_y=True)
|
| 158 |
+
X_train, X_val, y_train, y_val = sklearn.model_selection.train_test_split(X, y, random_state=0)
|
| 159 |
+
|
| 160 |
+
regressor_obj.fit(X_train, y_train)
|
| 161 |
+
y_pred = regressor_obj.predict(X_val)
|
| 162 |
+
|
| 163 |
+
error = sklearn.metrics.mean_squared_error(y_val, y_pred)
|
| 164 |
+
|
| 165 |
+
return error # An objective value linked with the Trial object.
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
study = optuna.create_study() # Create a new study.
|
| 169 |
+
study.optimize(objective, n_trials=100) # Invoke optimization of the objective function.
|
| 170 |
+
```
|
| 171 |
+
</details>
|
| 172 |
+
|
| 173 |
+
> [!NOTE]
|
| 174 |
+
> More examples can be found in [optuna/optuna-examples](https://github.com/optuna/optuna-examples).
|
| 175 |
+
>
|
| 176 |
+
> The examples cover diverse problem setups such as multi-objective optimization, constrained optimization, pruning, and distributed optimization.
|
| 177 |
+
|
| 178 |
+
## Installation
|
| 179 |
+
|
| 180 |
+
Optuna is available at [the Python Package Index](https://pypi.org/project/optuna/) and on [Anaconda Cloud](https://anaconda.org/conda-forge/optuna).
|
| 181 |
+
|
| 182 |
+
```bash
|
| 183 |
+
# PyPI
|
| 184 |
+
$ pip install optuna
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
```bash
|
| 188 |
+
# Anaconda Cloud
|
| 189 |
+
$ conda install -c conda-forge optuna
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
> [!IMPORTANT]
|
| 193 |
+
> Optuna supports Python 3.9 or newer.
|
| 194 |
+
|
| 195 |
+
## Integrations
|
| 196 |
+
|
| 197 |
+
Optuna has integration features with various third-party libraries. Integrations can be found in [optuna/optuna-integration](https://github.com/optuna/optuna-integration) and the document is available [here](https://optuna-integration.readthedocs.io/en/stable/index.html).
|
| 198 |
+
|
| 199 |
+
<details>
|
| 200 |
+
<summary>Supported integration libraries</summary>
|
| 201 |
+
|
| 202 |
+
* [Catboost](https://github.com/optuna/optuna-examples/tree/main/catboost/catboost_pruning.py)
|
| 203 |
+
* [Dask](https://github.com/optuna/optuna-examples/tree/main/dask/dask_simple.py)
|
| 204 |
+
* [fastai](https://github.com/optuna/optuna-examples/tree/main/fastai/fastai_simple.py)
|
| 205 |
+
* [Keras](https://github.com/optuna/optuna-examples/tree/main/keras/keras_integration.py)
|
| 206 |
+
* [LightGBM](https://github.com/optuna/optuna-examples/tree/main/lightgbm/lightgbm_integration.py)
|
| 207 |
+
* [PyTorch](https://github.com/optuna/optuna-examples/tree/main/pytorch/pytorch_simple.py)
|
| 208 |
+
* [PyTorch Ignite](https://github.com/optuna/optuna-examples/tree/main/pytorch/pytorch_ignite_simple.py)
|
| 209 |
+
* [PyTorch Lightning](https://github.com/optuna/optuna-examples/tree/main/pytorch/pytorch_lightning_simple.py)
|
| 210 |
+
* [TensorFlow](https://github.com/optuna/optuna-examples/tree/main/tensorflow/tensorflow_estimator_integration.py)
|
| 211 |
+
* [tf.keras](https://github.com/optuna/optuna-examples/tree/main/tfkeras/tfkeras_integration.py)
|
| 212 |
+
* [XGBoost](https://github.com/optuna/optuna-examples/tree/main/xgboost/xgboost_integration.py)
|
| 213 |
+
</details>
|
| 214 |
+
|
| 215 |
+
## Web Dashboard
|
| 216 |
+
|
| 217 |
+
[Optuna Dashboard](https://github.com/optuna/optuna-dashboard) is a real-time web dashboard for Optuna.
|
| 218 |
+
You can check the optimization history, hyperparameter importance, etc. in graphs and tables.
|
| 219 |
+
You don't need to create a Python script to call [Optuna's visualization](https://optuna.readthedocs.io/en/stable/reference/visualization/index.html) functions.
|
| 220 |
+
Feature requests and bug reports are welcome!
|
| 221 |
+
|
| 222 |
+

|
| 223 |
+
|
| 224 |
+
`optuna-dashboard` can be installed via pip:
|
| 225 |
+
|
| 226 |
+
```shell
|
| 227 |
+
$ pip install optuna-dashboard
|
| 228 |
+
```
|
| 229 |
+
|
| 230 |
+
> [!TIP]
|
| 231 |
+
> Please check out the convenience of Optuna Dashboard using the sample code below.
|
| 232 |
+
|
| 233 |
+
<details>
|
| 234 |
+
<summary>Sample code to launch Optuna Dashboard</summary>
|
| 235 |
+
|
| 236 |
+
Save the following code as `optimize_toy.py`.
|
| 237 |
+
|
| 238 |
+
```python
|
| 239 |
+
import optuna
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def objective(trial):
|
| 243 |
+
x1 = trial.suggest_float("x1", -100, 100)
|
| 244 |
+
x2 = trial.suggest_float("x2", -100, 100)
|
| 245 |
+
return x1**2 + 0.01 * x2**2
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
study = optuna.create_study(storage="sqlite:///db.sqlite3") # Create a new study with database.
|
| 249 |
+
study.optimize(objective, n_trials=100)
|
| 250 |
+
```
|
| 251 |
+
|
| 252 |
+
Then try the commands below:
|
| 253 |
+
|
| 254 |
+
```shell
|
| 255 |
+
# Run the study specified above
|
| 256 |
+
$ python optimize_toy.py
|
| 257 |
+
|
| 258 |
+
# Launch the dashboard based on the storage `sqlite:///db.sqlite3`
|
| 259 |
+
$ optuna-dashboard sqlite:///db.sqlite3
|
| 260 |
+
...
|
| 261 |
+
Listening on http://localhost:8080/
|
| 262 |
+
Hit Ctrl-C to quit.
|
| 263 |
+
```
|
| 264 |
+
|
| 265 |
+
</details>
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
## OptunaHub
|
| 269 |
+
|
| 270 |
+
[OptunaHub](https://hub.optuna.org/) is a feature-sharing platform for Optuna.
|
| 271 |
+
You can use the registered features and publish your packages.
|
| 272 |
+
|
| 273 |
+
### Use registered features
|
| 274 |
+
|
| 275 |
+
`optunahub` can be installed via pip:
|
| 276 |
+
|
| 277 |
+
```shell
|
| 278 |
+
$ pip install optunahub
|
| 279 |
+
# Install AutoSampler dependencies (CPU only is sufficient for PyTorch)
|
| 280 |
+
$ pip install cmaes scipy torch --extra-index-url https://download.pytorch.org/whl/cpu
|
| 281 |
+
```
|
| 282 |
+
|
| 283 |
+
You can load registered module with `optunahub.load_module`.
|
| 284 |
+
|
| 285 |
+
```python
|
| 286 |
+
import optuna
|
| 287 |
+
import optunahub
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def objective(trial: optuna.Trial) -> float:
|
| 291 |
+
x = trial.suggest_float("x", -5, 5)
|
| 292 |
+
y = trial.suggest_float("y", -5, 5)
|
| 293 |
+
return x**2 + y**2
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
module = optunahub.load_module(package="samplers/auto_sampler")
|
| 297 |
+
study = optuna.create_study(sampler=module.AutoSampler())
|
| 298 |
+
study.optimize(objective, n_trials=10)
|
| 299 |
+
|
| 300 |
+
print(study.best_trial.value, study.best_trial.params)
|
| 301 |
+
```
|
| 302 |
+
|
| 303 |
+
For more details, please refer to [the optunahub documentation](https://optuna.github.io/optunahub/).
|
| 304 |
+
|
| 305 |
+
### Publish your packages
|
| 306 |
+
|
| 307 |
+
You can publish your package via [optunahub-registry](https://github.com/optuna/optunahub-registry).
|
| 308 |
+
See the [Tutorials for Contributors](https://optuna.github.io/optunahub/tutorials_for_contributors.html) in OptunaHub.
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
## Communication
|
| 312 |
+
|
| 313 |
+
- [GitHub Discussions] for questions.
|
| 314 |
+
- [GitHub Issues] for bug reports and feature requests.
|
| 315 |
+
|
| 316 |
+
[GitHub Discussions]: https://github.com/optuna/optuna/discussions
|
| 317 |
+
[GitHub issues]: https://github.com/optuna/optuna/issues
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
## Contribution
|
| 321 |
+
|
| 322 |
+
Any contributions to Optuna are more than welcome!
|
| 323 |
+
|
| 324 |
+
If you are new to Optuna, please check the [good first issues](https://github.com/optuna/optuna/labels/good%20first%20issue). They are relatively simple, well-defined, and often good starting points for you to get familiar with the contribution workflow and other developers.
|
| 325 |
+
|
| 326 |
+
If you already have contributed to Optuna, we recommend the other [contribution-welcome issues](https://github.com/optuna/optuna/labels/contribution-welcome).
|
| 327 |
+
|
| 328 |
+
For general guidelines on how to contribute to the project, take a look at [CONTRIBUTING.md](./CONTRIBUTING.md).
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
## Reference
|
| 332 |
+
|
| 333 |
+
If you use Optuna in one of your research projects, please cite [our KDD paper](https://doi.org/10.1145/3292500.3330701) "Optuna: A Next-generation Hyperparameter Optimization Framework":
|
| 334 |
+
|
| 335 |
+
<details open>
|
| 336 |
+
<summary>BibTeX</summary>
|
| 337 |
+
|
| 338 |
+
```bibtex
|
| 339 |
+
@inproceedings{akiba2019optuna,
|
| 340 |
+
title={{O}ptuna: A Next-Generation Hyperparameter Optimization Framework},
|
| 341 |
+
author={Akiba, Takuya and Sano, Shotaro and Yanase, Toshihiko and Ohta, Takeru and Koyama, Masanori},
|
| 342 |
+
booktitle={The 25th ACM SIGKDD International Conference on Knowledge Discovery \& Data Mining},
|
| 343 |
+
pages={2623--2631},
|
| 344 |
+
year={2019}
|
| 345 |
+
}
|
| 346 |
+
```
|
| 347 |
+
</details>
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
## License
|
| 351 |
+
|
| 352 |
+
MIT License (see [LICENSE](./LICENSE)).
|
| 353 |
+
|
| 354 |
+
Optuna uses the codes from SciPy and fdlibm projects (see [LICENSE_THIRD_PARTY](./LICENSE_THIRD_PARTY)).
|
.cache/pip/http-v2/4/5/2/4/1/45241d61b1606b84c3825a9119b750e7cd16e5fac504d31f79203a8e
ADDED
|
Binary file (1.31 kB). View file
|
|
|
.cache/pip/http-v2/4/5/2/4/1/45241d61b1606b84c3825a9119b750e7cd16e5fac504d31f79203a8e.body
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: click
|
| 3 |
+
Version: 8.4.2
|
| 4 |
+
Summary: Composable command line interface toolkit
|
| 5 |
+
Maintainer-email: Pallets <contact@palletsprojects.com>
|
| 6 |
+
Requires-Python: >=3.10
|
| 7 |
+
Description-Content-Type: text/markdown
|
| 8 |
+
License-Expression: BSD-3-Clause
|
| 9 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 10 |
+
Classifier: Intended Audience :: Developers
|
| 11 |
+
Classifier: Operating System :: OS Independent
|
| 12 |
+
Classifier: Programming Language :: Python
|
| 13 |
+
Classifier: Typing :: Typed
|
| 14 |
+
License-File: LICENSE.txt
|
| 15 |
+
Requires-Dist: colorama; platform_system == 'Windows'
|
| 16 |
+
Project-URL: Changes, https://click.palletsprojects.com/page/changes/
|
| 17 |
+
Project-URL: Chat, https://discord.gg/pallets
|
| 18 |
+
Project-URL: Documentation, https://click.palletsprojects.com/
|
| 19 |
+
Project-URL: Donate, https://palletsprojects.com/donate
|
| 20 |
+
Project-URL: Source, https://github.com/pallets/click/
|
| 21 |
+
|
| 22 |
+
<div align="center"><img src="https://raw.githubusercontent.com/pallets/click/refs/heads/stable/docs/_static/click-name.svg" alt="" height="150"></div>
|
| 23 |
+
|
| 24 |
+
# Click
|
| 25 |
+
|
| 26 |
+
Click is a Python package for creating beautiful command line interfaces
|
| 27 |
+
in a composable way with as little code as necessary. It's the "Command
|
| 28 |
+
Line Interface Creation Kit". It's highly configurable but comes with
|
| 29 |
+
sensible defaults out of the box.
|
| 30 |
+
|
| 31 |
+
It aims to make the process of writing command line tools quick and fun
|
| 32 |
+
while also preventing any frustration caused by the inability to
|
| 33 |
+
implement an intended CLI API.
|
| 34 |
+
|
| 35 |
+
Click in three points:
|
| 36 |
+
|
| 37 |
+
- Arbitrary nesting of commands
|
| 38 |
+
- Automatic help page generation
|
| 39 |
+
- Supports lazy loading of subcommands at runtime
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
## A Simple Example
|
| 43 |
+
|
| 44 |
+
```python
|
| 45 |
+
import click
|
| 46 |
+
|
| 47 |
+
@click.command()
|
| 48 |
+
@click.option("--count", default=1, help="Number of greetings.")
|
| 49 |
+
@click.option("--name", prompt="Your name", help="The person to greet.")
|
| 50 |
+
def hello(count, name):
|
| 51 |
+
"""Simple program that greets NAME for a total of COUNT times."""
|
| 52 |
+
for _ in range(count):
|
| 53 |
+
click.echo(f"Hello, {name}!")
|
| 54 |
+
|
| 55 |
+
if __name__ == '__main__':
|
| 56 |
+
hello()
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
```
|
| 60 |
+
$ python hello.py --count=3
|
| 61 |
+
Your name: Click
|
| 62 |
+
Hello, Click!
|
| 63 |
+
Hello, Click!
|
| 64 |
+
Hello, Click!
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
## Donate
|
| 69 |
+
|
| 70 |
+
The Pallets organization develops and supports Click and other popular
|
| 71 |
+
packages. In order to grow the community of contributors and users, and
|
| 72 |
+
allow the maintainers to devote more time to the projects, [please
|
| 73 |
+
donate today][].
|
| 74 |
+
|
| 75 |
+
[please donate today]: https://palletsprojects.com/donate
|
| 76 |
+
|
| 77 |
+
## Contributing
|
| 78 |
+
|
| 79 |
+
See our [detailed contributing documentation][contrib] for many ways to
|
| 80 |
+
contribute, including reporting issues, requesting features, asking or answering
|
| 81 |
+
questions, and making PRs.
|
| 82 |
+
|
| 83 |
+
[contrib]: https://palletsprojects.com/contributing/
|
| 84 |
+
|
.cache/pip/http-v2/4/d/c/8/d/4dc8d567db4bc55c0684404c85a6b4572f87a99306be24cab65fbfae.body
ADDED
|
Binary file (16.2 kB). View file
|
|
|
.cache/pip/http-v2/5/9/1/a/0/591a0a7ea47d81cffb332bf5e1460e560ce743822558c6f345314d4b
ADDED
|
Binary file (1.23 kB). View file
|
|
|
.cache/pip/http-v2/5/9/1/a/0/591a0a7ea47d81cffb332bf5e1460e560ce743822558c6f345314d4b.body
ADDED
|
Binary file (18.1 kB). View file
|
|
|
.cache/pip/http-v2/5/e/c/8/b/5ec8b58bc827caa12672b72c08527dbd1c5456edeea815f1e76cb526
ADDED
|
Binary file (1.2 kB). View file
|
|
|
.cache/pip/http-v2/7/2/8/a/2/728a2f33f382f4dacf08f6df77aad6f3d889f819ba4fa3efad5ec7e4
ADDED
|
Binary file (1.9 kB). View file
|
|
|
.cache/pip/http-v2/7/5/c/7/6/75c76ba3da983fc745a6549a0de110dcd624d42b682204260c21f535
ADDED
|
Binary file (1.21 kB). View file
|
|
|
.cache/pip/http-v2/7/9/2/1/a/7921ac3318a5cdb592026cc26a94f7a2c1e1f7d3a1dc1e3857fd49f1
ADDED
|
Binary file (1.9 kB). View file
|
|
|
.cache/pip/http-v2/7/9/2/1/a/7921ac3318a5cdb592026cc26a94f7a2c1e1f7d3a1dc1e3857fd49f1.body
ADDED
|
Binary file (1.94 kB). View file
|
|
|
.cache/pip/http-v2/7/f/0/e/c/7f0ec35e0c3a1faba9aada2b4b15e64482162fc43af0f7193ee83003
ADDED
|
Binary file (1.2 kB). View file
|
|
|
.cache/pip/http-v2/b/1/f/5/d/b1f5dc01896eee598e8915be35e61304ad2b16363d00711f8576642c
ADDED
|
Binary file (1.9 kB). View file
|
|
|
.cache/pip/http-v2/b/7/8/c/d/b78cd723a0a817da9a40ee919588e074704b65517e7095f1b98b332b
ADDED
|
Binary file (1.2 kB). View file
|
|
|
.cache/pip/http-v2/b/e/5/9/9/be599e435b04e9191df28c1690b91394df11dcc43b78b8097f2cac95
ADDED
|
Binary file (1.9 kB). View file
|
|
|
.cache/pip/http-v2/b/e/5/9/9/be599e435b04e9191df28c1690b91394df11dcc43b78b8097f2cac95.body
ADDED
|
Binary file (4.53 kB). View file
|
|
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11-0.16.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: h11
|
| 3 |
+
Version: 0.16.0
|
| 4 |
+
Summary: A pure-Python, bring-your-own-I/O implementation of HTTP/1.1
|
| 5 |
+
Home-page: https://github.com/python-hyper/h11
|
| 6 |
+
Author: Nathaniel J. Smith
|
| 7 |
+
Author-email: njs@pobox.com
|
| 8 |
+
License: MIT
|
| 9 |
+
Classifier: Development Status :: 3 - Alpha
|
| 10 |
+
Classifier: Intended Audience :: Developers
|
| 11 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 12 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 13 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 14 |
+
Classifier: Programming Language :: Python :: 3
|
| 15 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 21 |
+
Classifier: Topic :: Internet :: WWW/HTTP
|
| 22 |
+
Classifier: Topic :: System :: Networking
|
| 23 |
+
Requires-Python: >=3.8
|
| 24 |
+
License-File: LICENSE.txt
|
| 25 |
+
Dynamic: author
|
| 26 |
+
Dynamic: author-email
|
| 27 |
+
Dynamic: classifier
|
| 28 |
+
Dynamic: description
|
| 29 |
+
Dynamic: home-page
|
| 30 |
+
Dynamic: license
|
| 31 |
+
Dynamic: license-file
|
| 32 |
+
Dynamic: requires-python
|
| 33 |
+
Dynamic: summary
|
| 34 |
+
|
| 35 |
+
h11
|
| 36 |
+
===
|
| 37 |
+
|
| 38 |
+
.. image:: https://travis-ci.org/python-hyper/h11.svg?branch=master
|
| 39 |
+
:target: https://travis-ci.org/python-hyper/h11
|
| 40 |
+
:alt: Automated test status
|
| 41 |
+
|
| 42 |
+
.. image:: https://codecov.io/gh/python-hyper/h11/branch/master/graph/badge.svg
|
| 43 |
+
:target: https://codecov.io/gh/python-hyper/h11
|
| 44 |
+
:alt: Test coverage
|
| 45 |
+
|
| 46 |
+
.. image:: https://readthedocs.org/projects/h11/badge/?version=latest
|
| 47 |
+
:target: http://h11.readthedocs.io/en/latest/?badge=latest
|
| 48 |
+
:alt: Documentation Status
|
| 49 |
+
|
| 50 |
+
This is a little HTTP/1.1 library written from scratch in Python,
|
| 51 |
+
heavily inspired by `hyper-h2 <https://hyper-h2.readthedocs.io/>`_.
|
| 52 |
+
|
| 53 |
+
It's a "bring-your-own-I/O" library; h11 contains no IO code
|
| 54 |
+
whatsoever. This means you can hook h11 up to your favorite network
|
| 55 |
+
API, and that could be anything you want: synchronous, threaded,
|
| 56 |
+
asynchronous, or your own implementation of `RFC 6214
|
| 57 |
+
<https://tools.ietf.org/html/rfc6214>`_ -- h11 won't judge you.
|
| 58 |
+
(Compare this to the current state of the art, where every time a `new
|
| 59 |
+
network API <https://trio.readthedocs.io/>`_ comes along then someone
|
| 60 |
+
gets to start over reimplementing the entire HTTP protocol from
|
| 61 |
+
scratch.) Cory Benfield made an `excellent blog post describing the
|
| 62 |
+
benefits of this approach
|
| 63 |
+
<https://lukasa.co.uk/2015/10/The_New_Hyper/>`_, or if you like video
|
| 64 |
+
then here's his `PyCon 2016 talk on the same theme
|
| 65 |
+
<https://www.youtube.com/watch?v=7cC3_jGwl_U>`_.
|
| 66 |
+
|
| 67 |
+
This also means that h11 is not immediately useful out of the box:
|
| 68 |
+
it's a toolkit for building programs that speak HTTP, not something
|
| 69 |
+
that could directly replace ``requests`` or ``twisted.web`` or
|
| 70 |
+
whatever. But h11 makes it much easier to implement something like
|
| 71 |
+
``requests`` or ``twisted.web``.
|
| 72 |
+
|
| 73 |
+
At a high level, working with h11 goes like this:
|
| 74 |
+
|
| 75 |
+
1) First, create an ``h11.Connection`` object to track the state of a
|
| 76 |
+
single HTTP/1.1 connection.
|
| 77 |
+
|
| 78 |
+
2) When you read data off the network, pass it to
|
| 79 |
+
``conn.receive_data(...)``; you'll get back a list of objects
|
| 80 |
+
representing high-level HTTP "events".
|
| 81 |
+
|
| 82 |
+
3) When you want to send a high-level HTTP event, create the
|
| 83 |
+
corresponding "event" object and pass it to ``conn.send(...)``;
|
| 84 |
+
this will give you back some bytes that you can then push out
|
| 85 |
+
through the network.
|
| 86 |
+
|
| 87 |
+
For example, a client might instantiate and then send a
|
| 88 |
+
``h11.Request`` object, then zero or more ``h11.Data`` objects for the
|
| 89 |
+
request body (e.g., if this is a POST), and then a
|
| 90 |
+
``h11.EndOfMessage`` to indicate the end of the message. Then the
|
| 91 |
+
server would then send back a ``h11.Response``, some ``h11.Data``, and
|
| 92 |
+
its own ``h11.EndOfMessage``. If either side violates the protocol,
|
| 93 |
+
you'll get a ``h11.ProtocolError`` exception.
|
| 94 |
+
|
| 95 |
+
h11 is suitable for implementing both servers and clients, and has a
|
| 96 |
+
pleasantly symmetric API: the events you send as a client are exactly
|
| 97 |
+
the ones that you receive as a server and vice-versa.
|
| 98 |
+
|
| 99 |
+
`Here's an example of a tiny HTTP client
|
| 100 |
+
<https://github.com/python-hyper/h11/blob/master/examples/basic-client.py>`_
|
| 101 |
+
|
| 102 |
+
It also has `a fine manual <https://h11.readthedocs.io/>`_.
|
| 103 |
+
|
| 104 |
+
FAQ
|
| 105 |
+
---
|
| 106 |
+
|
| 107 |
+
*Whyyyyy?*
|
| 108 |
+
|
| 109 |
+
I wanted to play with HTTP in `Curio
|
| 110 |
+
<https://curio.readthedocs.io/en/latest/tutorial.html>`__ and `Trio
|
| 111 |
+
<https://trio.readthedocs.io>`__, which at the time didn't have any
|
| 112 |
+
HTTP libraries. So I thought, no big deal, Python has, like, a dozen
|
| 113 |
+
different implementations of HTTP, surely I can find one that's
|
| 114 |
+
reusable. I didn't find one, but I did find Cory's call-to-arms
|
| 115 |
+
blog-post. So I figured, well, fine, if I have to implement HTTP from
|
| 116 |
+
scratch, at least I can make sure no-one *else* has to ever again.
|
| 117 |
+
|
| 118 |
+
*Should I use it?*
|
| 119 |
+
|
| 120 |
+
Maybe. You should be aware that it's a very young project. But, it's
|
| 121 |
+
feature complete and has an exhaustive test-suite and complete docs,
|
| 122 |
+
so the next step is for people to try using it and see how it goes
|
| 123 |
+
:-). If you do then please let us know -- if nothing else we'll want
|
| 124 |
+
to talk to you before making any incompatible changes!
|
| 125 |
+
|
| 126 |
+
*What are the features/limitations?*
|
| 127 |
+
|
| 128 |
+
Roughly speaking, it's trying to be a robust, complete, and non-hacky
|
| 129 |
+
implementation of the first "chapter" of the HTTP/1.1 spec: `RFC 7230:
|
| 130 |
+
HTTP/1.1 Message Syntax and Routing
|
| 131 |
+
<https://tools.ietf.org/html/rfc7230>`_. That is, it mostly focuses on
|
| 132 |
+
implementing HTTP at the level of taking bytes on and off the wire,
|
| 133 |
+
and the headers related to that, and tries to be anal about spec
|
| 134 |
+
conformance. It doesn't know about higher-level concerns like URL
|
| 135 |
+
routing, conditional GETs, cross-origin cookie policies, or content
|
| 136 |
+
negotiation. But it does know how to take care of framing,
|
| 137 |
+
cross-version differences in keep-alive handling, and the "obsolete
|
| 138 |
+
line folding" rule, so you can focus your energies on the hard /
|
| 139 |
+
interesting parts for your application, and it tries to support the
|
| 140 |
+
full specification in the sense that any useful HTTP/1.1 conformant
|
| 141 |
+
application should be able to use h11.
|
| 142 |
+
|
| 143 |
+
It's pure Python, and has no dependencies outside of the standard
|
| 144 |
+
library.
|
| 145 |
+
|
| 146 |
+
It has a test suite with 100.0% coverage for both statements and
|
| 147 |
+
branches.
|
| 148 |
+
|
| 149 |
+
Currently it supports Python 3 (testing on 3.8-3.12) and PyPy 3.
|
| 150 |
+
The last Python 2-compatible version was h11 0.11.x.
|
| 151 |
+
(Originally it had a Cython wrapper for `http-parser
|
| 152 |
+
<https://github.com/nodejs/http-parser>`_ and a beautiful nested state
|
| 153 |
+
machine implemented with ``yield from`` to postprocess the output. But
|
| 154 |
+
I had to take these out -- the new *parser* needs fewer lines-of-code
|
| 155 |
+
than the old *parser wrapper*, is written in pure Python, uses no
|
| 156 |
+
exotic language syntax, and has more features. It's sad, really; that
|
| 157 |
+
old state machine was really slick. I just need a few sentences here
|
| 158 |
+
to mourn that.)
|
| 159 |
+
|
| 160 |
+
I don't know how fast it is. I haven't benchmarked or profiled it yet,
|
| 161 |
+
so it's probably got a few pointless hot spots, and I've been trying
|
| 162 |
+
to err on the side of simplicity and robustness instead of
|
| 163 |
+
micro-optimization. But at the architectural level I tried hard to
|
| 164 |
+
avoid fundamentally bad decisions, e.g., I believe that all the
|
| 165 |
+
parsing algorithms remain linear-time even in the face of pathological
|
| 166 |
+
input like slowloris, and there are no byte-by-byte loops. (I also
|
| 167 |
+
believe that it maintains bounded memory usage in the face of
|
| 168 |
+
arbitrary/pathological input.)
|
| 169 |
+
|
| 170 |
+
The whole library is ~800 lines-of-code. You can read and understand
|
| 171 |
+
the whole thing in less than an hour. Most of the energy invested in
|
| 172 |
+
this so far has been spent on trying to keep things simple by
|
| 173 |
+
minimizing special-cases and ad hoc state manipulation; even though it
|
| 174 |
+
is now quite small and simple, I'm still annoyed that I haven't
|
| 175 |
+
figured out how to make it even smaller and simpler. (Unfortunately,
|
| 176 |
+
HTTP does not lend itself to simplicity.)
|
| 177 |
+
|
| 178 |
+
The API is ~feature complete and I don't expect the general outlines
|
| 179 |
+
to change much, but you can't judge an API's ergonomics until you
|
| 180 |
+
actually document and use it, so I'd expect some changes in the
|
| 181 |
+
details.
|
| 182 |
+
|
| 183 |
+
*How do I try it?*
|
| 184 |
+
|
| 185 |
+
.. code-block:: sh
|
| 186 |
+
|
| 187 |
+
$ pip install h11
|
| 188 |
+
$ git clone git@github.com:python-hyper/h11
|
| 189 |
+
$ cd h11/examples
|
| 190 |
+
$ python basic-client.py
|
| 191 |
+
|
| 192 |
+
and go from there.
|
| 193 |
+
|
| 194 |
+
*License?*
|
| 195 |
+
|
| 196 |
+
MIT
|
| 197 |
+
|
| 198 |
+
*Code of conduct?*
|
| 199 |
+
|
| 200 |
+
Contributors are requested to follow our `code of conduct
|
| 201 |
+
<https://github.com/python-hyper/h11/blob/master/CODE_OF_CONDUCT.md>`_ in
|
| 202 |
+
all project spaces.
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11-0.16.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
h11/__init__.py,sha256=iO1KzkSO42yZ6ffg-VMgbx_ZVTWGUY00nRYEWn-s3kY,1507
|
| 2 |
+
h11/_abnf.py,sha256=ybixr0xsupnkA6GFAyMubuXF6Tc1lb_hF890NgCsfNc,4815
|
| 3 |
+
h11/_connection.py,sha256=k9YRVf6koZqbttBW36xSWaJpWdZwa-xQVU9AHEo9DuI,26863
|
| 4 |
+
h11/_events.py,sha256=I97aXoal1Wu7dkL548BANBUCkOIbe-x5CioYA9IBY14,11792
|
| 5 |
+
h11/_headers.py,sha256=P7D-lBNxHwdLZPLimmYwrPG-9ZkjElvvJZJdZAgSP-4,10412
|
| 6 |
+
h11/_readers.py,sha256=a4RypORUCC3d0q_kxPuBIM7jTD8iLt5X91TH0FsduN4,8590
|
| 7 |
+
h11/_receivebuffer.py,sha256=xrspsdsNgWFxRfQcTXxR8RrdjRXXTK0Io5cQYWpJ1Ws,5252
|
| 8 |
+
h11/_state.py,sha256=_5LG_BGR8FCcFQeBPH-TMHgm_-B-EUcWCnQof_9XjFE,13231
|
| 9 |
+
h11/_util.py,sha256=LWkkjXyJaFlAy6Lt39w73UStklFT5ovcvo0TkY7RYuk,4888
|
| 10 |
+
h11/_version.py,sha256=GVSsbPSPDcOuF6ptfIiXnVJoaEm3ygXbMnqlr_Giahw,686
|
| 11 |
+
h11/_writers.py,sha256=oFKm6PtjeHfbj4RLX7VB7KDc1gIY53gXG3_HR9ltmTA,5081
|
| 12 |
+
h11/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7
|
| 13 |
+
h11-0.16.0.dist-info/licenses/LICENSE.txt,sha256=N9tbuFkm2yikJ6JYZ_ELEjIAOuob5pzLhRE4rbjm82E,1124
|
| 14 |
+
h11-0.16.0.dist-info/METADATA,sha256=KPMmCYrAn8unm48YD5YIfIQf4kViFct7hyqcfVzRnWQ,8348
|
| 15 |
+
h11-0.16.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
|
| 16 |
+
h11-0.16.0.dist-info/top_level.txt,sha256=F7dC4jl3zeh8TGHEPaWJrMbeuoWbS379Gwdi-Yvdcis,4
|
| 17 |
+
h11-0.16.0.dist-info/RECORD,,
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11-0.16.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (78.1.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11-0.16.0.dist-info/licenses/LICENSE.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The MIT License (MIT)
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2016 Nathaniel J. Smith <njs@pobox.com> and other contributors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining
|
| 6 |
+
a copy of this software and associated documentation files (the
|
| 7 |
+
"Software"), to deal in the Software without restriction, including
|
| 8 |
+
without limitation the rights to use, copy, modify, merge, publish,
|
| 9 |
+
distribute, sublicense, and/or sell copies of the Software, and to
|
| 10 |
+
permit persons to whom the Software is furnished to do so, subject to
|
| 11 |
+
the following conditions:
|
| 12 |
+
|
| 13 |
+
The above copyright notice and this permission notice shall be
|
| 14 |
+
included in all copies or substantial portions of the Software.
|
| 15 |
+
|
| 16 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 17 |
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 18 |
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 19 |
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
| 20 |
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
| 21 |
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
| 22 |
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11-0.16.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
h11
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/__init__.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# A highish-level implementation of the HTTP/1.1 wire protocol (RFC 7230),
|
| 2 |
+
# containing no networking code at all, loosely modelled on hyper-h2's generic
|
| 3 |
+
# implementation of HTTP/2 (and in particular the h2.connection.H2Connection
|
| 4 |
+
# class). There's still a bunch of subtle details you need to get right if you
|
| 5 |
+
# want to make this actually useful, because it doesn't implement all the
|
| 6 |
+
# semantics to check that what you're asking to write to the wire is sensible,
|
| 7 |
+
# but at least it gets you out of dealing with the wire itself.
|
| 8 |
+
|
| 9 |
+
from h11._connection import Connection, NEED_DATA, PAUSED
|
| 10 |
+
from h11._events import (
|
| 11 |
+
ConnectionClosed,
|
| 12 |
+
Data,
|
| 13 |
+
EndOfMessage,
|
| 14 |
+
Event,
|
| 15 |
+
InformationalResponse,
|
| 16 |
+
Request,
|
| 17 |
+
Response,
|
| 18 |
+
)
|
| 19 |
+
from h11._state import (
|
| 20 |
+
CLIENT,
|
| 21 |
+
CLOSED,
|
| 22 |
+
DONE,
|
| 23 |
+
ERROR,
|
| 24 |
+
IDLE,
|
| 25 |
+
MIGHT_SWITCH_PROTOCOL,
|
| 26 |
+
MUST_CLOSE,
|
| 27 |
+
SEND_BODY,
|
| 28 |
+
SEND_RESPONSE,
|
| 29 |
+
SERVER,
|
| 30 |
+
SWITCHED_PROTOCOL,
|
| 31 |
+
)
|
| 32 |
+
from h11._util import LocalProtocolError, ProtocolError, RemoteProtocolError
|
| 33 |
+
from h11._version import __version__
|
| 34 |
+
|
| 35 |
+
PRODUCT_ID = "python-h11/" + __version__
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
__all__ = (
|
| 39 |
+
"Connection",
|
| 40 |
+
"NEED_DATA",
|
| 41 |
+
"PAUSED",
|
| 42 |
+
"ConnectionClosed",
|
| 43 |
+
"Data",
|
| 44 |
+
"EndOfMessage",
|
| 45 |
+
"Event",
|
| 46 |
+
"InformationalResponse",
|
| 47 |
+
"Request",
|
| 48 |
+
"Response",
|
| 49 |
+
"CLIENT",
|
| 50 |
+
"CLOSED",
|
| 51 |
+
"DONE",
|
| 52 |
+
"ERROR",
|
| 53 |
+
"IDLE",
|
| 54 |
+
"MUST_CLOSE",
|
| 55 |
+
"SEND_BODY",
|
| 56 |
+
"SEND_RESPONSE",
|
| 57 |
+
"SERVER",
|
| 58 |
+
"SWITCHED_PROTOCOL",
|
| 59 |
+
"ProtocolError",
|
| 60 |
+
"LocalProtocolError",
|
| 61 |
+
"RemoteProtocolError",
|
| 62 |
+
)
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_abnf.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# We use native strings for all the re patterns, to take advantage of string
|
| 2 |
+
# formatting, and then convert to bytestrings when compiling the final re
|
| 3 |
+
# objects.
|
| 4 |
+
|
| 5 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#whitespace
|
| 6 |
+
# OWS = *( SP / HTAB )
|
| 7 |
+
# ; optional whitespace
|
| 8 |
+
OWS = r"[ \t]*"
|
| 9 |
+
|
| 10 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.token.separators
|
| 11 |
+
# token = 1*tchar
|
| 12 |
+
#
|
| 13 |
+
# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
|
| 14 |
+
# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
|
| 15 |
+
# / DIGIT / ALPHA
|
| 16 |
+
# ; any VCHAR, except delimiters
|
| 17 |
+
token = r"[-!#$%&'*+.^_`|~0-9a-zA-Z]+"
|
| 18 |
+
|
| 19 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#header.fields
|
| 20 |
+
# field-name = token
|
| 21 |
+
field_name = token
|
| 22 |
+
|
| 23 |
+
# The standard says:
|
| 24 |
+
#
|
| 25 |
+
# field-value = *( field-content / obs-fold )
|
| 26 |
+
# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
|
| 27 |
+
# field-vchar = VCHAR / obs-text
|
| 28 |
+
# obs-fold = CRLF 1*( SP / HTAB )
|
| 29 |
+
# ; obsolete line folding
|
| 30 |
+
# ; see Section 3.2.4
|
| 31 |
+
#
|
| 32 |
+
# https://tools.ietf.org/html/rfc5234#appendix-B.1
|
| 33 |
+
#
|
| 34 |
+
# VCHAR = %x21-7E
|
| 35 |
+
# ; visible (printing) characters
|
| 36 |
+
#
|
| 37 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.quoted-string
|
| 38 |
+
# obs-text = %x80-FF
|
| 39 |
+
#
|
| 40 |
+
# However, the standard definition of field-content is WRONG! It disallows
|
| 41 |
+
# fields containing a single visible character surrounded by whitespace,
|
| 42 |
+
# e.g. "foo a bar".
|
| 43 |
+
#
|
| 44 |
+
# See: https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189
|
| 45 |
+
#
|
| 46 |
+
# So our definition of field_content attempts to fix it up...
|
| 47 |
+
#
|
| 48 |
+
# Also, we allow lots of control characters, because apparently people assume
|
| 49 |
+
# that they're legal in practice (e.g., google analytics makes cookies with
|
| 50 |
+
# \x01 in them!):
|
| 51 |
+
# https://github.com/python-hyper/h11/issues/57
|
| 52 |
+
# We still don't allow NUL or whitespace, because those are often treated as
|
| 53 |
+
# meta-characters and letting them through can lead to nasty issues like SSRF.
|
| 54 |
+
vchar = r"[\x21-\x7e]"
|
| 55 |
+
vchar_or_obs_text = r"[^\x00\s]"
|
| 56 |
+
field_vchar = vchar_or_obs_text
|
| 57 |
+
field_content = r"{field_vchar}+(?:[ \t]+{field_vchar}+)*".format(**globals())
|
| 58 |
+
|
| 59 |
+
# We handle obs-fold at a different level, and our fixed-up field_content
|
| 60 |
+
# already grows to swallow the whole value, so ? instead of *
|
| 61 |
+
field_value = r"({field_content})?".format(**globals())
|
| 62 |
+
|
| 63 |
+
# header-field = field-name ":" OWS field-value OWS
|
| 64 |
+
header_field = (
|
| 65 |
+
r"(?P<field_name>{field_name})"
|
| 66 |
+
r":"
|
| 67 |
+
r"{OWS}"
|
| 68 |
+
r"(?P<field_value>{field_value})"
|
| 69 |
+
r"{OWS}".format(**globals())
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#request.line
|
| 73 |
+
#
|
| 74 |
+
# request-line = method SP request-target SP HTTP-version CRLF
|
| 75 |
+
# method = token
|
| 76 |
+
# HTTP-version = HTTP-name "/" DIGIT "." DIGIT
|
| 77 |
+
# HTTP-name = %x48.54.54.50 ; "HTTP", case-sensitive
|
| 78 |
+
#
|
| 79 |
+
# request-target is complicated (see RFC 7230 sec 5.3) -- could be path, full
|
| 80 |
+
# URL, host+port (for connect), or even "*", but in any case we are guaranteed
|
| 81 |
+
# that it contists of the visible printing characters.
|
| 82 |
+
method = token
|
| 83 |
+
request_target = r"{vchar}+".format(**globals())
|
| 84 |
+
http_version = r"HTTP/(?P<http_version>[0-9]\.[0-9])"
|
| 85 |
+
request_line = (
|
| 86 |
+
r"(?P<method>{method})"
|
| 87 |
+
r" "
|
| 88 |
+
r"(?P<target>{request_target})"
|
| 89 |
+
r" "
|
| 90 |
+
r"{http_version}".format(**globals())
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#status.line
|
| 94 |
+
#
|
| 95 |
+
# status-line = HTTP-version SP status-code SP reason-phrase CRLF
|
| 96 |
+
# status-code = 3DIGIT
|
| 97 |
+
# reason-phrase = *( HTAB / SP / VCHAR / obs-text )
|
| 98 |
+
status_code = r"[0-9]{3}"
|
| 99 |
+
reason_phrase = r"([ \t]|{vchar_or_obs_text})*".format(**globals())
|
| 100 |
+
status_line = (
|
| 101 |
+
r"{http_version}"
|
| 102 |
+
r" "
|
| 103 |
+
r"(?P<status_code>{status_code})"
|
| 104 |
+
# However, there are apparently a few too many servers out there that just
|
| 105 |
+
# leave out the reason phrase:
|
| 106 |
+
# https://github.com/scrapy/scrapy/issues/345#issuecomment-281756036
|
| 107 |
+
# https://github.com/seanmonstar/httparse/issues/29
|
| 108 |
+
# so make it optional. ?: is a non-capturing group.
|
| 109 |
+
r"(?: (?P<reason>{reason_phrase}))?".format(**globals())
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
HEXDIG = r"[0-9A-Fa-f]"
|
| 113 |
+
# Actually
|
| 114 |
+
#
|
| 115 |
+
# chunk-size = 1*HEXDIG
|
| 116 |
+
#
|
| 117 |
+
# but we impose an upper-limit to avoid ridiculosity. len(str(2**64)) == 20
|
| 118 |
+
chunk_size = r"({HEXDIG}){{1,20}}".format(**globals())
|
| 119 |
+
# Actually
|
| 120 |
+
#
|
| 121 |
+
# chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
|
| 122 |
+
#
|
| 123 |
+
# but we aren't parsing the things so we don't really care.
|
| 124 |
+
chunk_ext = r";.*"
|
| 125 |
+
chunk_header = (
|
| 126 |
+
r"(?P<chunk_size>{chunk_size})"
|
| 127 |
+
r"(?P<chunk_ext>{chunk_ext})?"
|
| 128 |
+
r"{OWS}\r\n".format(
|
| 129 |
+
**globals()
|
| 130 |
+
) # Even though the specification does not allow for extra whitespaces,
|
| 131 |
+
# we are lenient with trailing whitespaces because some servers on the wild use it.
|
| 132 |
+
)
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_connection.py
ADDED
|
@@ -0,0 +1,659 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This contains the main Connection class. Everything in h11 revolves around
|
| 2 |
+
# this.
|
| 3 |
+
from typing import (
|
| 4 |
+
Any,
|
| 5 |
+
Callable,
|
| 6 |
+
cast,
|
| 7 |
+
Dict,
|
| 8 |
+
List,
|
| 9 |
+
Optional,
|
| 10 |
+
overload,
|
| 11 |
+
Tuple,
|
| 12 |
+
Type,
|
| 13 |
+
Union,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
from ._events import (
|
| 17 |
+
ConnectionClosed,
|
| 18 |
+
Data,
|
| 19 |
+
EndOfMessage,
|
| 20 |
+
Event,
|
| 21 |
+
InformationalResponse,
|
| 22 |
+
Request,
|
| 23 |
+
Response,
|
| 24 |
+
)
|
| 25 |
+
from ._headers import get_comma_header, has_expect_100_continue, set_comma_header
|
| 26 |
+
from ._readers import READERS, ReadersType
|
| 27 |
+
from ._receivebuffer import ReceiveBuffer
|
| 28 |
+
from ._state import (
|
| 29 |
+
_SWITCH_CONNECT,
|
| 30 |
+
_SWITCH_UPGRADE,
|
| 31 |
+
CLIENT,
|
| 32 |
+
ConnectionState,
|
| 33 |
+
DONE,
|
| 34 |
+
ERROR,
|
| 35 |
+
MIGHT_SWITCH_PROTOCOL,
|
| 36 |
+
SEND_BODY,
|
| 37 |
+
SERVER,
|
| 38 |
+
SWITCHED_PROTOCOL,
|
| 39 |
+
)
|
| 40 |
+
from ._util import ( # Import the internal things we need
|
| 41 |
+
LocalProtocolError,
|
| 42 |
+
RemoteProtocolError,
|
| 43 |
+
Sentinel,
|
| 44 |
+
)
|
| 45 |
+
from ._writers import WRITERS, WritersType
|
| 46 |
+
|
| 47 |
+
# Everything in __all__ gets re-exported as part of the h11 public API.
|
| 48 |
+
__all__ = ["Connection", "NEED_DATA", "PAUSED"]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class NEED_DATA(Sentinel, metaclass=Sentinel):
|
| 52 |
+
pass
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class PAUSED(Sentinel, metaclass=Sentinel):
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# If we ever have this much buffered without it making a complete parseable
|
| 60 |
+
# event, we error out. The only time we really buffer is when reading the
|
| 61 |
+
# request/response line + headers together, so this is effectively the limit on
|
| 62 |
+
# the size of that.
|
| 63 |
+
#
|
| 64 |
+
# Some precedents for defaults:
|
| 65 |
+
# - node.js: 80 * 1024
|
| 66 |
+
# - tomcat: 8 * 1024
|
| 67 |
+
# - IIS: 16 * 1024
|
| 68 |
+
# - Apache: <8 KiB per line>
|
| 69 |
+
DEFAULT_MAX_INCOMPLETE_EVENT_SIZE = 16 * 1024
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# RFC 7230's rules for connection lifecycles:
|
| 73 |
+
# - If either side says they want to close the connection, then the connection
|
| 74 |
+
# must close.
|
| 75 |
+
# - HTTP/1.1 defaults to keep-alive unless someone says Connection: close
|
| 76 |
+
# - HTTP/1.0 defaults to close unless both sides say Connection: keep-alive
|
| 77 |
+
# (and even this is a mess -- e.g. if you're implementing a proxy then
|
| 78 |
+
# sending Connection: keep-alive is forbidden).
|
| 79 |
+
#
|
| 80 |
+
# We simplify life by simply not supporting keep-alive with HTTP/1.0 peers. So
|
| 81 |
+
# our rule is:
|
| 82 |
+
# - If someone says Connection: close, we will close
|
| 83 |
+
# - If someone uses HTTP/1.0, we will close.
|
| 84 |
+
def _keep_alive(event: Union[Request, Response]) -> bool:
|
| 85 |
+
connection = get_comma_header(event.headers, b"connection")
|
| 86 |
+
if b"close" in connection:
|
| 87 |
+
return False
|
| 88 |
+
if getattr(event, "http_version", b"1.1") < b"1.1":
|
| 89 |
+
return False
|
| 90 |
+
return True
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _body_framing(
|
| 94 |
+
request_method: bytes, event: Union[Request, Response]
|
| 95 |
+
) -> Tuple[str, Union[Tuple[()], Tuple[int]]]:
|
| 96 |
+
# Called when we enter SEND_BODY to figure out framing information for
|
| 97 |
+
# this body.
|
| 98 |
+
#
|
| 99 |
+
# These are the only two events that can trigger a SEND_BODY state:
|
| 100 |
+
assert type(event) in (Request, Response)
|
| 101 |
+
# Returns one of:
|
| 102 |
+
#
|
| 103 |
+
# ("content-length", count)
|
| 104 |
+
# ("chunked", ())
|
| 105 |
+
# ("http/1.0", ())
|
| 106 |
+
#
|
| 107 |
+
# which are (lookup key, *args) for constructing body reader/writer
|
| 108 |
+
# objects.
|
| 109 |
+
#
|
| 110 |
+
# Reference: https://tools.ietf.org/html/rfc7230#section-3.3.3
|
| 111 |
+
#
|
| 112 |
+
# Step 1: some responses always have an empty body, regardless of what the
|
| 113 |
+
# headers say.
|
| 114 |
+
if type(event) is Response:
|
| 115 |
+
if (
|
| 116 |
+
event.status_code in (204, 304)
|
| 117 |
+
or request_method == b"HEAD"
|
| 118 |
+
or (request_method == b"CONNECT" and 200 <= event.status_code < 300)
|
| 119 |
+
):
|
| 120 |
+
return ("content-length", (0,))
|
| 121 |
+
# Section 3.3.3 also lists another case -- responses with status_code
|
| 122 |
+
# < 200. For us these are InformationalResponses, not Responses, so
|
| 123 |
+
# they can't get into this function in the first place.
|
| 124 |
+
assert event.status_code >= 200
|
| 125 |
+
|
| 126 |
+
# Step 2: check for Transfer-Encoding (T-E beats C-L):
|
| 127 |
+
transfer_encodings = get_comma_header(event.headers, b"transfer-encoding")
|
| 128 |
+
if transfer_encodings:
|
| 129 |
+
assert transfer_encodings == [b"chunked"]
|
| 130 |
+
return ("chunked", ())
|
| 131 |
+
|
| 132 |
+
# Step 3: check for Content-Length
|
| 133 |
+
content_lengths = get_comma_header(event.headers, b"content-length")
|
| 134 |
+
if content_lengths:
|
| 135 |
+
return ("content-length", (int(content_lengths[0]),))
|
| 136 |
+
|
| 137 |
+
# Step 4: no applicable headers; fallback/default depends on type
|
| 138 |
+
if type(event) is Request:
|
| 139 |
+
return ("content-length", (0,))
|
| 140 |
+
else:
|
| 141 |
+
return ("http/1.0", ())
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
################################################################
|
| 145 |
+
#
|
| 146 |
+
# The main Connection class
|
| 147 |
+
#
|
| 148 |
+
################################################################
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class Connection:
|
| 152 |
+
"""An object encapsulating the state of an HTTP connection.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
our_role: If you're implementing a client, pass :data:`h11.CLIENT`. If
|
| 156 |
+
you're implementing a server, pass :data:`h11.SERVER`.
|
| 157 |
+
|
| 158 |
+
max_incomplete_event_size (int):
|
| 159 |
+
The maximum number of bytes we're willing to buffer of an
|
| 160 |
+
incomplete event. In practice this mostly sets a limit on the
|
| 161 |
+
maximum size of the request/response line + headers. If this is
|
| 162 |
+
exceeded, then :meth:`next_event` will raise
|
| 163 |
+
:exc:`RemoteProtocolError`.
|
| 164 |
+
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def __init__(
|
| 168 |
+
self,
|
| 169 |
+
our_role: Type[Sentinel],
|
| 170 |
+
max_incomplete_event_size: int = DEFAULT_MAX_INCOMPLETE_EVENT_SIZE,
|
| 171 |
+
) -> None:
|
| 172 |
+
self._max_incomplete_event_size = max_incomplete_event_size
|
| 173 |
+
# State and role tracking
|
| 174 |
+
if our_role not in (CLIENT, SERVER):
|
| 175 |
+
raise ValueError(f"expected CLIENT or SERVER, not {our_role!r}")
|
| 176 |
+
self.our_role = our_role
|
| 177 |
+
self.their_role: Type[Sentinel]
|
| 178 |
+
if our_role is CLIENT:
|
| 179 |
+
self.their_role = SERVER
|
| 180 |
+
else:
|
| 181 |
+
self.their_role = CLIENT
|
| 182 |
+
self._cstate = ConnectionState()
|
| 183 |
+
|
| 184 |
+
# Callables for converting data->events or vice-versa given the
|
| 185 |
+
# current state
|
| 186 |
+
self._writer = self._get_io_object(self.our_role, None, WRITERS)
|
| 187 |
+
self._reader = self._get_io_object(self.their_role, None, READERS)
|
| 188 |
+
|
| 189 |
+
# Holds any unprocessed received data
|
| 190 |
+
self._receive_buffer = ReceiveBuffer()
|
| 191 |
+
# If this is true, then it indicates that the incoming connection was
|
| 192 |
+
# closed *after* the end of whatever's in self._receive_buffer:
|
| 193 |
+
self._receive_buffer_closed = False
|
| 194 |
+
|
| 195 |
+
# Extra bits of state that don't fit into the state machine.
|
| 196 |
+
#
|
| 197 |
+
# These two are only used to interpret framing headers for figuring
|
| 198 |
+
# out how to read/write response bodies. their_http_version is also
|
| 199 |
+
# made available as a convenient public API.
|
| 200 |
+
self.their_http_version: Optional[bytes] = None
|
| 201 |
+
self._request_method: Optional[bytes] = None
|
| 202 |
+
# This is pure flow-control and doesn't at all affect the set of legal
|
| 203 |
+
# transitions, so no need to bother ConnectionState with it:
|
| 204 |
+
self.client_is_waiting_for_100_continue = False
|
| 205 |
+
|
| 206 |
+
@property
|
| 207 |
+
def states(self) -> Dict[Type[Sentinel], Type[Sentinel]]:
|
| 208 |
+
"""A dictionary like::
|
| 209 |
+
|
| 210 |
+
{CLIENT: <client state>, SERVER: <server state>}
|
| 211 |
+
|
| 212 |
+
See :ref:`state-machine` for details.
|
| 213 |
+
|
| 214 |
+
"""
|
| 215 |
+
return dict(self._cstate.states)
|
| 216 |
+
|
| 217 |
+
@property
|
| 218 |
+
def our_state(self) -> Type[Sentinel]:
|
| 219 |
+
"""The current state of whichever role we are playing. See
|
| 220 |
+
:ref:`state-machine` for details.
|
| 221 |
+
"""
|
| 222 |
+
return self._cstate.states[self.our_role]
|
| 223 |
+
|
| 224 |
+
@property
|
| 225 |
+
def their_state(self) -> Type[Sentinel]:
|
| 226 |
+
"""The current state of whichever role we are NOT playing. See
|
| 227 |
+
:ref:`state-machine` for details.
|
| 228 |
+
"""
|
| 229 |
+
return self._cstate.states[self.their_role]
|
| 230 |
+
|
| 231 |
+
@property
|
| 232 |
+
def they_are_waiting_for_100_continue(self) -> bool:
|
| 233 |
+
return self.their_role is CLIENT and self.client_is_waiting_for_100_continue
|
| 234 |
+
|
| 235 |
+
def start_next_cycle(self) -> None:
|
| 236 |
+
"""Attempt to reset our connection state for a new request/response
|
| 237 |
+
cycle.
|
| 238 |
+
|
| 239 |
+
If both client and server are in :data:`DONE` state, then resets them
|
| 240 |
+
both to :data:`IDLE` state in preparation for a new request/response
|
| 241 |
+
cycle on this same connection. Otherwise, raises a
|
| 242 |
+
:exc:`LocalProtocolError`.
|
| 243 |
+
|
| 244 |
+
See :ref:`keepalive-and-pipelining`.
|
| 245 |
+
|
| 246 |
+
"""
|
| 247 |
+
old_states = dict(self._cstate.states)
|
| 248 |
+
self._cstate.start_next_cycle()
|
| 249 |
+
self._request_method = None
|
| 250 |
+
# self.their_http_version gets left alone, since it presumably lasts
|
| 251 |
+
# beyond a single request/response cycle
|
| 252 |
+
assert not self.client_is_waiting_for_100_continue
|
| 253 |
+
self._respond_to_state_changes(old_states)
|
| 254 |
+
|
| 255 |
+
def _process_error(self, role: Type[Sentinel]) -> None:
|
| 256 |
+
old_states = dict(self._cstate.states)
|
| 257 |
+
self._cstate.process_error(role)
|
| 258 |
+
self._respond_to_state_changes(old_states)
|
| 259 |
+
|
| 260 |
+
def _server_switch_event(self, event: Event) -> Optional[Type[Sentinel]]:
|
| 261 |
+
if type(event) is InformationalResponse and event.status_code == 101:
|
| 262 |
+
return _SWITCH_UPGRADE
|
| 263 |
+
if type(event) is Response:
|
| 264 |
+
if (
|
| 265 |
+
_SWITCH_CONNECT in self._cstate.pending_switch_proposals
|
| 266 |
+
and 200 <= event.status_code < 300
|
| 267 |
+
):
|
| 268 |
+
return _SWITCH_CONNECT
|
| 269 |
+
return None
|
| 270 |
+
|
| 271 |
+
# All events go through here
|
| 272 |
+
def _process_event(self, role: Type[Sentinel], event: Event) -> None:
|
| 273 |
+
# First, pass the event through the state machine to make sure it
|
| 274 |
+
# succeeds.
|
| 275 |
+
old_states = dict(self._cstate.states)
|
| 276 |
+
if role is CLIENT and type(event) is Request:
|
| 277 |
+
if event.method == b"CONNECT":
|
| 278 |
+
self._cstate.process_client_switch_proposal(_SWITCH_CONNECT)
|
| 279 |
+
if get_comma_header(event.headers, b"upgrade"):
|
| 280 |
+
self._cstate.process_client_switch_proposal(_SWITCH_UPGRADE)
|
| 281 |
+
server_switch_event = None
|
| 282 |
+
if role is SERVER:
|
| 283 |
+
server_switch_event = self._server_switch_event(event)
|
| 284 |
+
self._cstate.process_event(role, type(event), server_switch_event)
|
| 285 |
+
|
| 286 |
+
# Then perform the updates triggered by it.
|
| 287 |
+
|
| 288 |
+
if type(event) is Request:
|
| 289 |
+
self._request_method = event.method
|
| 290 |
+
|
| 291 |
+
if role is self.their_role and type(event) in (
|
| 292 |
+
Request,
|
| 293 |
+
Response,
|
| 294 |
+
InformationalResponse,
|
| 295 |
+
):
|
| 296 |
+
event = cast(Union[Request, Response, InformationalResponse], event)
|
| 297 |
+
self.their_http_version = event.http_version
|
| 298 |
+
|
| 299 |
+
# Keep alive handling
|
| 300 |
+
#
|
| 301 |
+
# RFC 7230 doesn't really say what one should do if Connection: close
|
| 302 |
+
# shows up on a 1xx InformationalResponse. I think the idea is that
|
| 303 |
+
# this is not supposed to happen. In any case, if it does happen, we
|
| 304 |
+
# ignore it.
|
| 305 |
+
if type(event) in (Request, Response) and not _keep_alive(
|
| 306 |
+
cast(Union[Request, Response], event)
|
| 307 |
+
):
|
| 308 |
+
self._cstate.process_keep_alive_disabled()
|
| 309 |
+
|
| 310 |
+
# 100-continue
|
| 311 |
+
if type(event) is Request and has_expect_100_continue(event):
|
| 312 |
+
self.client_is_waiting_for_100_continue = True
|
| 313 |
+
if type(event) in (InformationalResponse, Response):
|
| 314 |
+
self.client_is_waiting_for_100_continue = False
|
| 315 |
+
if role is CLIENT and type(event) in (Data, EndOfMessage):
|
| 316 |
+
self.client_is_waiting_for_100_continue = False
|
| 317 |
+
|
| 318 |
+
self._respond_to_state_changes(old_states, event)
|
| 319 |
+
|
| 320 |
+
def _get_io_object(
|
| 321 |
+
self,
|
| 322 |
+
role: Type[Sentinel],
|
| 323 |
+
event: Optional[Event],
|
| 324 |
+
io_dict: Union[ReadersType, WritersType],
|
| 325 |
+
) -> Optional[Callable[..., Any]]:
|
| 326 |
+
# event may be None; it's only used when entering SEND_BODY
|
| 327 |
+
state = self._cstate.states[role]
|
| 328 |
+
if state is SEND_BODY:
|
| 329 |
+
# Special case: the io_dict has a dict of reader/writer factories
|
| 330 |
+
# that depend on the request/response framing.
|
| 331 |
+
framing_type, args = _body_framing(
|
| 332 |
+
cast(bytes, self._request_method), cast(Union[Request, Response], event)
|
| 333 |
+
)
|
| 334 |
+
return io_dict[SEND_BODY][framing_type](*args) # type: ignore[index]
|
| 335 |
+
else:
|
| 336 |
+
# General case: the io_dict just has the appropriate reader/writer
|
| 337 |
+
# for this state
|
| 338 |
+
return io_dict.get((role, state)) # type: ignore[return-value]
|
| 339 |
+
|
| 340 |
+
# This must be called after any action that might have caused
|
| 341 |
+
# self._cstate.states to change.
|
| 342 |
+
def _respond_to_state_changes(
|
| 343 |
+
self,
|
| 344 |
+
old_states: Dict[Type[Sentinel], Type[Sentinel]],
|
| 345 |
+
event: Optional[Event] = None,
|
| 346 |
+
) -> None:
|
| 347 |
+
# Update reader/writer
|
| 348 |
+
if self.our_state != old_states[self.our_role]:
|
| 349 |
+
self._writer = self._get_io_object(self.our_role, event, WRITERS)
|
| 350 |
+
if self.their_state != old_states[self.their_role]:
|
| 351 |
+
self._reader = self._get_io_object(self.their_role, event, READERS)
|
| 352 |
+
|
| 353 |
+
@property
|
| 354 |
+
def trailing_data(self) -> Tuple[bytes, bool]:
|
| 355 |
+
"""Data that has been received, but not yet processed, represented as
|
| 356 |
+
a tuple with two elements, where the first is a byte-string containing
|
| 357 |
+
the unprocessed data itself, and the second is a bool that is True if
|
| 358 |
+
the receive connection was closed.
|
| 359 |
+
|
| 360 |
+
See :ref:`switching-protocols` for discussion of why you'd want this.
|
| 361 |
+
"""
|
| 362 |
+
return (bytes(self._receive_buffer), self._receive_buffer_closed)
|
| 363 |
+
|
| 364 |
+
def receive_data(self, data: bytes) -> None:
|
| 365 |
+
"""Add data to our internal receive buffer.
|
| 366 |
+
|
| 367 |
+
This does not actually do any processing on the data, just stores
|
| 368 |
+
it. To trigger processing, you have to call :meth:`next_event`.
|
| 369 |
+
|
| 370 |
+
Args:
|
| 371 |
+
data (:term:`bytes-like object`):
|
| 372 |
+
The new data that was just received.
|
| 373 |
+
|
| 374 |
+
Special case: If *data* is an empty byte-string like ``b""``,
|
| 375 |
+
then this indicates that the remote side has closed the
|
| 376 |
+
connection (end of file). Normally this is convenient, because
|
| 377 |
+
standard Python APIs like :meth:`file.read` or
|
| 378 |
+
:meth:`socket.recv` use ``b""`` to indicate end-of-file, while
|
| 379 |
+
other failures to read are indicated using other mechanisms
|
| 380 |
+
like raising :exc:`TimeoutError`. When using such an API you
|
| 381 |
+
can just blindly pass through whatever you get from ``read``
|
| 382 |
+
to :meth:`receive_data`, and everything will work.
|
| 383 |
+
|
| 384 |
+
But, if you have an API where reading an empty string is a
|
| 385 |
+
valid non-EOF condition, then you need to be aware of this and
|
| 386 |
+
make sure to check for such strings and avoid passing them to
|
| 387 |
+
:meth:`receive_data`.
|
| 388 |
+
|
| 389 |
+
Returns:
|
| 390 |
+
Nothing, but after calling this you should call :meth:`next_event`
|
| 391 |
+
to parse the newly received data.
|
| 392 |
+
|
| 393 |
+
Raises:
|
| 394 |
+
RuntimeError:
|
| 395 |
+
Raised if you pass an empty *data*, indicating EOF, and then
|
| 396 |
+
pass a non-empty *data*, indicating more data that somehow
|
| 397 |
+
arrived after the EOF.
|
| 398 |
+
|
| 399 |
+
(Calling ``receive_data(b"")`` multiple times is fine,
|
| 400 |
+
and equivalent to calling it once.)
|
| 401 |
+
|
| 402 |
+
"""
|
| 403 |
+
if data:
|
| 404 |
+
if self._receive_buffer_closed:
|
| 405 |
+
raise RuntimeError("received close, then received more data?")
|
| 406 |
+
self._receive_buffer += data
|
| 407 |
+
else:
|
| 408 |
+
self._receive_buffer_closed = True
|
| 409 |
+
|
| 410 |
+
def _extract_next_receive_event(
|
| 411 |
+
self,
|
| 412 |
+
) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]:
|
| 413 |
+
state = self.their_state
|
| 414 |
+
# We don't pause immediately when they enter DONE, because even in
|
| 415 |
+
# DONE state we can still process a ConnectionClosed() event. But
|
| 416 |
+
# if we have data in our buffer, then we definitely aren't getting
|
| 417 |
+
# a ConnectionClosed() immediately and we need to pause.
|
| 418 |
+
if state is DONE and self._receive_buffer:
|
| 419 |
+
return PAUSED
|
| 420 |
+
if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL:
|
| 421 |
+
return PAUSED
|
| 422 |
+
assert self._reader is not None
|
| 423 |
+
event = self._reader(self._receive_buffer)
|
| 424 |
+
if event is None:
|
| 425 |
+
if not self._receive_buffer and self._receive_buffer_closed:
|
| 426 |
+
# In some unusual cases (basically just HTTP/1.0 bodies), EOF
|
| 427 |
+
# triggers an actual protocol event; in that case, we want to
|
| 428 |
+
# return that event, and then the state will change and we'll
|
| 429 |
+
# get called again to generate the actual ConnectionClosed().
|
| 430 |
+
if hasattr(self._reader, "read_eof"):
|
| 431 |
+
event = self._reader.read_eof()
|
| 432 |
+
else:
|
| 433 |
+
event = ConnectionClosed()
|
| 434 |
+
if event is None:
|
| 435 |
+
event = NEED_DATA
|
| 436 |
+
return event # type: ignore[no-any-return]
|
| 437 |
+
|
| 438 |
+
def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]:
|
| 439 |
+
"""Parse the next event out of our receive buffer, update our internal
|
| 440 |
+
state, and return it.
|
| 441 |
+
|
| 442 |
+
This is a mutating operation -- think of it like calling :func:`next`
|
| 443 |
+
on an iterator.
|
| 444 |
+
|
| 445 |
+
Returns:
|
| 446 |
+
: One of three things:
|
| 447 |
+
|
| 448 |
+
1) An event object -- see :ref:`events`.
|
| 449 |
+
|
| 450 |
+
2) The special constant :data:`NEED_DATA`, which indicates that
|
| 451 |
+
you need to read more data from your socket and pass it to
|
| 452 |
+
:meth:`receive_data` before this method will be able to return
|
| 453 |
+
any more events.
|
| 454 |
+
|
| 455 |
+
3) The special constant :data:`PAUSED`, which indicates that we
|
| 456 |
+
are not in a state where we can process incoming data (usually
|
| 457 |
+
because the peer has finished their part of the current
|
| 458 |
+
request/response cycle, and you have not yet called
|
| 459 |
+
:meth:`start_next_cycle`). See :ref:`flow-control` for details.
|
| 460 |
+
|
| 461 |
+
Raises:
|
| 462 |
+
RemoteProtocolError:
|
| 463 |
+
The peer has misbehaved. You should close the connection
|
| 464 |
+
(possibly after sending some kind of 4xx response).
|
| 465 |
+
|
| 466 |
+
Once this method returns :class:`ConnectionClosed` once, then all
|
| 467 |
+
subsequent calls will also return :class:`ConnectionClosed`.
|
| 468 |
+
|
| 469 |
+
If this method raises any exception besides :exc:`RemoteProtocolError`
|
| 470 |
+
then that's a bug -- if it happens please file a bug report!
|
| 471 |
+
|
| 472 |
+
If this method raises any exception then it also sets
|
| 473 |
+
:attr:`Connection.their_state` to :data:`ERROR` -- see
|
| 474 |
+
:ref:`error-handling` for discussion.
|
| 475 |
+
|
| 476 |
+
"""
|
| 477 |
+
|
| 478 |
+
if self.their_state is ERROR:
|
| 479 |
+
raise RemoteProtocolError("Can't receive data when peer state is ERROR")
|
| 480 |
+
try:
|
| 481 |
+
event = self._extract_next_receive_event()
|
| 482 |
+
if event not in [NEED_DATA, PAUSED]:
|
| 483 |
+
self._process_event(self.their_role, cast(Event, event))
|
| 484 |
+
if event is NEED_DATA:
|
| 485 |
+
if len(self._receive_buffer) > self._max_incomplete_event_size:
|
| 486 |
+
# 431 is "Request header fields too large" which is pretty
|
| 487 |
+
# much the only situation where we can get here
|
| 488 |
+
raise RemoteProtocolError(
|
| 489 |
+
"Receive buffer too long", error_status_hint=431
|
| 490 |
+
)
|
| 491 |
+
if self._receive_buffer_closed:
|
| 492 |
+
# We're still trying to complete some event, but that's
|
| 493 |
+
# never going to happen because no more data is coming
|
| 494 |
+
raise RemoteProtocolError("peer unexpectedly closed connection")
|
| 495 |
+
return event
|
| 496 |
+
except BaseException as exc:
|
| 497 |
+
self._process_error(self.their_role)
|
| 498 |
+
if isinstance(exc, LocalProtocolError):
|
| 499 |
+
exc._reraise_as_remote_protocol_error()
|
| 500 |
+
else:
|
| 501 |
+
raise
|
| 502 |
+
|
| 503 |
+
@overload
|
| 504 |
+
def send(self, event: ConnectionClosed) -> None:
|
| 505 |
+
...
|
| 506 |
+
|
| 507 |
+
@overload
|
| 508 |
+
def send(
|
| 509 |
+
self, event: Union[Request, InformationalResponse, Response, Data, EndOfMessage]
|
| 510 |
+
) -> bytes:
|
| 511 |
+
...
|
| 512 |
+
|
| 513 |
+
@overload
|
| 514 |
+
def send(self, event: Event) -> Optional[bytes]:
|
| 515 |
+
...
|
| 516 |
+
|
| 517 |
+
def send(self, event: Event) -> Optional[bytes]:
|
| 518 |
+
"""Convert a high-level event into bytes that can be sent to the peer,
|
| 519 |
+
while updating our internal state machine.
|
| 520 |
+
|
| 521 |
+
Args:
|
| 522 |
+
event: The :ref:`event <events>` to send.
|
| 523 |
+
|
| 524 |
+
Returns:
|
| 525 |
+
If ``type(event) is ConnectionClosed``, then returns
|
| 526 |
+
``None``. Otherwise, returns a :term:`bytes-like object`.
|
| 527 |
+
|
| 528 |
+
Raises:
|
| 529 |
+
LocalProtocolError:
|
| 530 |
+
Sending this event at this time would violate our
|
| 531 |
+
understanding of the HTTP/1.1 protocol.
|
| 532 |
+
|
| 533 |
+
If this method raises any exception then it also sets
|
| 534 |
+
:attr:`Connection.our_state` to :data:`ERROR` -- see
|
| 535 |
+
:ref:`error-handling` for discussion.
|
| 536 |
+
|
| 537 |
+
"""
|
| 538 |
+
data_list = self.send_with_data_passthrough(event)
|
| 539 |
+
if data_list is None:
|
| 540 |
+
return None
|
| 541 |
+
else:
|
| 542 |
+
return b"".join(data_list)
|
| 543 |
+
|
| 544 |
+
def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]:
|
| 545 |
+
"""Identical to :meth:`send`, except that in situations where
|
| 546 |
+
:meth:`send` returns a single :term:`bytes-like object`, this instead
|
| 547 |
+
returns a list of them -- and when sending a :class:`Data` event, this
|
| 548 |
+
list is guaranteed to contain the exact object you passed in as
|
| 549 |
+
:attr:`Data.data`. See :ref:`sendfile` for discussion.
|
| 550 |
+
|
| 551 |
+
"""
|
| 552 |
+
if self.our_state is ERROR:
|
| 553 |
+
raise LocalProtocolError("Can't send data when our state is ERROR")
|
| 554 |
+
try:
|
| 555 |
+
if type(event) is Response:
|
| 556 |
+
event = self._clean_up_response_headers_for_sending(event)
|
| 557 |
+
# We want to call _process_event before calling the writer,
|
| 558 |
+
# because if someone tries to do something invalid then this will
|
| 559 |
+
# give a sensible error message, while our writers all just assume
|
| 560 |
+
# they will only receive valid events. But, _process_event might
|
| 561 |
+
# change self._writer. So we have to do a little dance:
|
| 562 |
+
writer = self._writer
|
| 563 |
+
self._process_event(self.our_role, event)
|
| 564 |
+
if type(event) is ConnectionClosed:
|
| 565 |
+
return None
|
| 566 |
+
else:
|
| 567 |
+
# In any situation where writer is None, process_event should
|
| 568 |
+
# have raised ProtocolError
|
| 569 |
+
assert writer is not None
|
| 570 |
+
data_list: List[bytes] = []
|
| 571 |
+
writer(event, data_list.append)
|
| 572 |
+
return data_list
|
| 573 |
+
except:
|
| 574 |
+
self._process_error(self.our_role)
|
| 575 |
+
raise
|
| 576 |
+
|
| 577 |
+
def send_failed(self) -> None:
|
| 578 |
+
"""Notify the state machine that we failed to send the data it gave
|
| 579 |
+
us.
|
| 580 |
+
|
| 581 |
+
This causes :attr:`Connection.our_state` to immediately become
|
| 582 |
+
:data:`ERROR` -- see :ref:`error-handling` for discussion.
|
| 583 |
+
|
| 584 |
+
"""
|
| 585 |
+
self._process_error(self.our_role)
|
| 586 |
+
|
| 587 |
+
# When sending a Response, we take responsibility for a few things:
|
| 588 |
+
#
|
| 589 |
+
# - Sometimes you MUST set Connection: close. We take care of those
|
| 590 |
+
# times. (You can also set it yourself if you want, and if you do then
|
| 591 |
+
# we'll respect that and close the connection at the right time. But you
|
| 592 |
+
# don't have to worry about that unless you want to.)
|
| 593 |
+
#
|
| 594 |
+
# - The user has to set Content-Length if they want it. Otherwise, for
|
| 595 |
+
# responses that have bodies (e.g. not HEAD), then we will automatically
|
| 596 |
+
# select the right mechanism for streaming a body of unknown length,
|
| 597 |
+
# which depends on depending on the peer's HTTP version.
|
| 598 |
+
#
|
| 599 |
+
# This function's *only* responsibility is making sure headers are set up
|
| 600 |
+
# right -- everything downstream just looks at the headers. There are no
|
| 601 |
+
# side channels.
|
| 602 |
+
def _clean_up_response_headers_for_sending(self, response: Response) -> Response:
|
| 603 |
+
assert type(response) is Response
|
| 604 |
+
|
| 605 |
+
headers = response.headers
|
| 606 |
+
need_close = False
|
| 607 |
+
|
| 608 |
+
# HEAD requests need some special handling: they always act like they
|
| 609 |
+
# have Content-Length: 0, and that's how _body_framing treats
|
| 610 |
+
# them. But their headers are supposed to match what we would send if
|
| 611 |
+
# the request was a GET. (Technically there is one deviation allowed:
|
| 612 |
+
# we're allowed to leave out the framing headers -- see
|
| 613 |
+
# https://tools.ietf.org/html/rfc7231#section-4.3.2 . But it's just as
|
| 614 |
+
# easy to get them right.)
|
| 615 |
+
method_for_choosing_headers = cast(bytes, self._request_method)
|
| 616 |
+
if method_for_choosing_headers == b"HEAD":
|
| 617 |
+
method_for_choosing_headers = b"GET"
|
| 618 |
+
framing_type, _ = _body_framing(method_for_choosing_headers, response)
|
| 619 |
+
if framing_type in ("chunked", "http/1.0"):
|
| 620 |
+
# This response has a body of unknown length.
|
| 621 |
+
# If our peer is HTTP/1.1, we use Transfer-Encoding: chunked
|
| 622 |
+
# If our peer is HTTP/1.0, we use no framing headers, and close the
|
| 623 |
+
# connection afterwards.
|
| 624 |
+
#
|
| 625 |
+
# Make sure to clear Content-Length (in principle user could have
|
| 626 |
+
# set both and then we ignored Content-Length b/c
|
| 627 |
+
# Transfer-Encoding overwrote it -- this would be naughty of them,
|
| 628 |
+
# but the HTTP spec says that if our peer does this then we have
|
| 629 |
+
# to fix it instead of erroring out, so we'll accord the user the
|
| 630 |
+
# same respect).
|
| 631 |
+
headers = set_comma_header(headers, b"content-length", [])
|
| 632 |
+
if self.their_http_version is None or self.their_http_version < b"1.1":
|
| 633 |
+
# Either we never got a valid request and are sending back an
|
| 634 |
+
# error (their_http_version is None), so we assume the worst;
|
| 635 |
+
# or else we did get a valid HTTP/1.0 request, so we know that
|
| 636 |
+
# they don't understand chunked encoding.
|
| 637 |
+
headers = set_comma_header(headers, b"transfer-encoding", [])
|
| 638 |
+
# This is actually redundant ATM, since currently we
|
| 639 |
+
# unconditionally disable keep-alive when talking to HTTP/1.0
|
| 640 |
+
# peers. But let's be defensive just in case we add
|
| 641 |
+
# Connection: keep-alive support later:
|
| 642 |
+
if self._request_method != b"HEAD":
|
| 643 |
+
need_close = True
|
| 644 |
+
else:
|
| 645 |
+
headers = set_comma_header(headers, b"transfer-encoding", [b"chunked"])
|
| 646 |
+
|
| 647 |
+
if not self._cstate.keep_alive or need_close:
|
| 648 |
+
# Make sure Connection: close is set
|
| 649 |
+
connection = set(get_comma_header(headers, b"connection"))
|
| 650 |
+
connection.discard(b"keep-alive")
|
| 651 |
+
connection.add(b"close")
|
| 652 |
+
headers = set_comma_header(headers, b"connection", sorted(connection))
|
| 653 |
+
|
| 654 |
+
return Response(
|
| 655 |
+
headers=headers,
|
| 656 |
+
status_code=response.status_code,
|
| 657 |
+
http_version=response.http_version,
|
| 658 |
+
reason=response.reason,
|
| 659 |
+
)
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_events.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
# High level events that make up HTTP/1.1 conversations. Loosely inspired by
|
| 2 |
+
# the corresponding events in hyper-h2:
|
| 3 |
+
#
|
| 4 |
+
# http://python-hyper.org/h2/en/stable/api.html#events
|
| 5 |
+
#
|
| 6 |
+
# Don't subclass these. Stuff will break.
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
from abc import ABC
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
from typing import List, Tuple, Union
|
| 12 |
+
|
| 13 |
+
from ._abnf import method, request_target
|
| 14 |
+
from ._headers import Headers, normalize_and_validate
|
| 15 |
+
from ._util import bytesify, LocalProtocolError, validate
|
| 16 |
+
|
| 17 |
+
# Everything in __all__ gets re-exported as part of the h11 public API.
|
| 18 |
+
__all__ = [
|
| 19 |
+
"Event",
|
| 20 |
+
"Request",
|
| 21 |
+
"InformationalResponse",
|
| 22 |
+
"Response",
|
| 23 |
+
"Data",
|
| 24 |
+
"EndOfMessage",
|
| 25 |
+
"ConnectionClosed",
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
method_re = re.compile(method.encode("ascii"))
|
| 29 |
+
request_target_re = re.compile(request_target.encode("ascii"))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class Event(ABC):
|
| 33 |
+
"""
|
| 34 |
+
Base class for h11 events.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
__slots__ = ()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass(init=False, frozen=True)
|
| 41 |
+
class Request(Event):
|
| 42 |
+
"""The beginning of an HTTP request.
|
| 43 |
+
|
| 44 |
+
Fields:
|
| 45 |
+
|
| 46 |
+
.. attribute:: method
|
| 47 |
+
|
| 48 |
+
An HTTP method, e.g. ``b"GET"`` or ``b"POST"``. Always a byte
|
| 49 |
+
string. :term:`Bytes-like objects <bytes-like object>` and native
|
| 50 |
+
strings containing only ascii characters will be automatically
|
| 51 |
+
converted to byte strings.
|
| 52 |
+
|
| 53 |
+
.. attribute:: target
|
| 54 |
+
|
| 55 |
+
The target of an HTTP request, e.g. ``b"/index.html"``, or one of the
|
| 56 |
+
more exotic formats described in `RFC 7320, section 5.3
|
| 57 |
+
<https://tools.ietf.org/html/rfc7230#section-5.3>`_. Always a byte
|
| 58 |
+
string. :term:`Bytes-like objects <bytes-like object>` and native
|
| 59 |
+
strings containing only ascii characters will be automatically
|
| 60 |
+
converted to byte strings.
|
| 61 |
+
|
| 62 |
+
.. attribute:: headers
|
| 63 |
+
|
| 64 |
+
Request headers, represented as a list of (name, value) pairs. See
|
| 65 |
+
:ref:`the header normalization rules <headers-format>` for details.
|
| 66 |
+
|
| 67 |
+
.. attribute:: http_version
|
| 68 |
+
|
| 69 |
+
The HTTP protocol version, represented as a byte string like
|
| 70 |
+
``b"1.1"``. See :ref:`the HTTP version normalization rules
|
| 71 |
+
<http_version-format>` for details.
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
__slots__ = ("method", "headers", "target", "http_version")
|
| 76 |
+
|
| 77 |
+
method: bytes
|
| 78 |
+
headers: Headers
|
| 79 |
+
target: bytes
|
| 80 |
+
http_version: bytes
|
| 81 |
+
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
*,
|
| 85 |
+
method: Union[bytes, str],
|
| 86 |
+
headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]],
|
| 87 |
+
target: Union[bytes, str],
|
| 88 |
+
http_version: Union[bytes, str] = b"1.1",
|
| 89 |
+
_parsed: bool = False,
|
| 90 |
+
) -> None:
|
| 91 |
+
super().__init__()
|
| 92 |
+
if isinstance(headers, Headers):
|
| 93 |
+
object.__setattr__(self, "headers", headers)
|
| 94 |
+
else:
|
| 95 |
+
object.__setattr__(
|
| 96 |
+
self, "headers", normalize_and_validate(headers, _parsed=_parsed)
|
| 97 |
+
)
|
| 98 |
+
if not _parsed:
|
| 99 |
+
object.__setattr__(self, "method", bytesify(method))
|
| 100 |
+
object.__setattr__(self, "target", bytesify(target))
|
| 101 |
+
object.__setattr__(self, "http_version", bytesify(http_version))
|
| 102 |
+
else:
|
| 103 |
+
object.__setattr__(self, "method", method)
|
| 104 |
+
object.__setattr__(self, "target", target)
|
| 105 |
+
object.__setattr__(self, "http_version", http_version)
|
| 106 |
+
|
| 107 |
+
# "A server MUST respond with a 400 (Bad Request) status code to any
|
| 108 |
+
# HTTP/1.1 request message that lacks a Host header field and to any
|
| 109 |
+
# request message that contains more than one Host header field or a
|
| 110 |
+
# Host header field with an invalid field-value."
|
| 111 |
+
# -- https://tools.ietf.org/html/rfc7230#section-5.4
|
| 112 |
+
host_count = 0
|
| 113 |
+
for name, value in self.headers:
|
| 114 |
+
if name == b"host":
|
| 115 |
+
host_count += 1
|
| 116 |
+
if self.http_version == b"1.1" and host_count == 0:
|
| 117 |
+
raise LocalProtocolError("Missing mandatory Host: header")
|
| 118 |
+
if host_count > 1:
|
| 119 |
+
raise LocalProtocolError("Found multiple Host: headers")
|
| 120 |
+
|
| 121 |
+
validate(method_re, self.method, "Illegal method characters")
|
| 122 |
+
validate(request_target_re, self.target, "Illegal target characters")
|
| 123 |
+
|
| 124 |
+
# This is an unhashable type.
|
| 125 |
+
__hash__ = None # type: ignore
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@dataclass(init=False, frozen=True)
|
| 129 |
+
class _ResponseBase(Event):
|
| 130 |
+
__slots__ = ("headers", "http_version", "reason", "status_code")
|
| 131 |
+
|
| 132 |
+
headers: Headers
|
| 133 |
+
http_version: bytes
|
| 134 |
+
reason: bytes
|
| 135 |
+
status_code: int
|
| 136 |
+
|
| 137 |
+
def __init__(
|
| 138 |
+
self,
|
| 139 |
+
*,
|
| 140 |
+
headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]],
|
| 141 |
+
status_code: int,
|
| 142 |
+
http_version: Union[bytes, str] = b"1.1",
|
| 143 |
+
reason: Union[bytes, str] = b"",
|
| 144 |
+
_parsed: bool = False,
|
| 145 |
+
) -> None:
|
| 146 |
+
super().__init__()
|
| 147 |
+
if isinstance(headers, Headers):
|
| 148 |
+
object.__setattr__(self, "headers", headers)
|
| 149 |
+
else:
|
| 150 |
+
object.__setattr__(
|
| 151 |
+
self, "headers", normalize_and_validate(headers, _parsed=_parsed)
|
| 152 |
+
)
|
| 153 |
+
if not _parsed:
|
| 154 |
+
object.__setattr__(self, "reason", bytesify(reason))
|
| 155 |
+
object.__setattr__(self, "http_version", bytesify(http_version))
|
| 156 |
+
if not isinstance(status_code, int):
|
| 157 |
+
raise LocalProtocolError("status code must be integer")
|
| 158 |
+
# Because IntEnum objects are instances of int, but aren't
|
| 159 |
+
# duck-compatible (sigh), see gh-72.
|
| 160 |
+
object.__setattr__(self, "status_code", int(status_code))
|
| 161 |
+
else:
|
| 162 |
+
object.__setattr__(self, "reason", reason)
|
| 163 |
+
object.__setattr__(self, "http_version", http_version)
|
| 164 |
+
object.__setattr__(self, "status_code", status_code)
|
| 165 |
+
|
| 166 |
+
self.__post_init__()
|
| 167 |
+
|
| 168 |
+
def __post_init__(self) -> None:
|
| 169 |
+
pass
|
| 170 |
+
|
| 171 |
+
# This is an unhashable type.
|
| 172 |
+
__hash__ = None # type: ignore
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@dataclass(init=False, frozen=True)
|
| 176 |
+
class InformationalResponse(_ResponseBase):
|
| 177 |
+
"""An HTTP informational response.
|
| 178 |
+
|
| 179 |
+
Fields:
|
| 180 |
+
|
| 181 |
+
.. attribute:: status_code
|
| 182 |
+
|
| 183 |
+
The status code of this response, as an integer. For an
|
| 184 |
+
:class:`InformationalResponse`, this is always in the range [100,
|
| 185 |
+
200).
|
| 186 |
+
|
| 187 |
+
.. attribute:: headers
|
| 188 |
+
|
| 189 |
+
Request headers, represented as a list of (name, value) pairs. See
|
| 190 |
+
:ref:`the header normalization rules <headers-format>` for
|
| 191 |
+
details.
|
| 192 |
+
|
| 193 |
+
.. attribute:: http_version
|
| 194 |
+
|
| 195 |
+
The HTTP protocol version, represented as a byte string like
|
| 196 |
+
``b"1.1"``. See :ref:`the HTTP version normalization rules
|
| 197 |
+
<http_version-format>` for details.
|
| 198 |
+
|
| 199 |
+
.. attribute:: reason
|
| 200 |
+
|
| 201 |
+
The reason phrase of this response, as a byte string. For example:
|
| 202 |
+
``b"OK"``, or ``b"Not Found"``.
|
| 203 |
+
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
def __post_init__(self) -> None:
|
| 207 |
+
if not (100 <= self.status_code < 200):
|
| 208 |
+
raise LocalProtocolError(
|
| 209 |
+
"InformationalResponse status_code should be in range "
|
| 210 |
+
"[100, 200), not {}".format(self.status_code)
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
# This is an unhashable type.
|
| 214 |
+
__hash__ = None # type: ignore
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@dataclass(init=False, frozen=True)
|
| 218 |
+
class Response(_ResponseBase):
|
| 219 |
+
"""The beginning of an HTTP response.
|
| 220 |
+
|
| 221 |
+
Fields:
|
| 222 |
+
|
| 223 |
+
.. attribute:: status_code
|
| 224 |
+
|
| 225 |
+
The status code of this response, as an integer. For an
|
| 226 |
+
:class:`Response`, this is always in the range [200,
|
| 227 |
+
1000).
|
| 228 |
+
|
| 229 |
+
.. attribute:: headers
|
| 230 |
+
|
| 231 |
+
Request headers, represented as a list of (name, value) pairs. See
|
| 232 |
+
:ref:`the header normalization rules <headers-format>` for details.
|
| 233 |
+
|
| 234 |
+
.. attribute:: http_version
|
| 235 |
+
|
| 236 |
+
The HTTP protocol version, represented as a byte string like
|
| 237 |
+
``b"1.1"``. See :ref:`the HTTP version normalization rules
|
| 238 |
+
<http_version-format>` for details.
|
| 239 |
+
|
| 240 |
+
.. attribute:: reason
|
| 241 |
+
|
| 242 |
+
The reason phrase of this response, as a byte string. For example:
|
| 243 |
+
``b"OK"``, or ``b"Not Found"``.
|
| 244 |
+
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
def __post_init__(self) -> None:
|
| 248 |
+
if not (200 <= self.status_code < 1000):
|
| 249 |
+
raise LocalProtocolError(
|
| 250 |
+
"Response status_code should be in range [200, 1000), not {}".format(
|
| 251 |
+
self.status_code
|
| 252 |
+
)
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# This is an unhashable type.
|
| 256 |
+
__hash__ = None # type: ignore
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@dataclass(init=False, frozen=True)
|
| 260 |
+
class Data(Event):
|
| 261 |
+
"""Part of an HTTP message body.
|
| 262 |
+
|
| 263 |
+
Fields:
|
| 264 |
+
|
| 265 |
+
.. attribute:: data
|
| 266 |
+
|
| 267 |
+
A :term:`bytes-like object` containing part of a message body. Or, if
|
| 268 |
+
using the ``combine=False`` argument to :meth:`Connection.send`, then
|
| 269 |
+
any object that your socket writing code knows what to do with, and for
|
| 270 |
+
which calling :func:`len` returns the number of bytes that will be
|
| 271 |
+
written -- see :ref:`sendfile` for details.
|
| 272 |
+
|
| 273 |
+
.. attribute:: chunk_start
|
| 274 |
+
|
| 275 |
+
A marker that indicates whether this data object is from the start of a
|
| 276 |
+
chunked transfer encoding chunk. This field is ignored when when a Data
|
| 277 |
+
event is provided to :meth:`Connection.send`: it is only valid on
|
| 278 |
+
events emitted from :meth:`Connection.next_event`. You probably
|
| 279 |
+
shouldn't use this attribute at all; see
|
| 280 |
+
:ref:`chunk-delimiters-are-bad` for details.
|
| 281 |
+
|
| 282 |
+
.. attribute:: chunk_end
|
| 283 |
+
|
| 284 |
+
A marker that indicates whether this data object is the last for a
|
| 285 |
+
given chunked transfer encoding chunk. This field is ignored when when
|
| 286 |
+
a Data event is provided to :meth:`Connection.send`: it is only valid
|
| 287 |
+
on events emitted from :meth:`Connection.next_event`. You probably
|
| 288 |
+
shouldn't use this attribute at all; see
|
| 289 |
+
:ref:`chunk-delimiters-are-bad` for details.
|
| 290 |
+
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
__slots__ = ("data", "chunk_start", "chunk_end")
|
| 294 |
+
|
| 295 |
+
data: bytes
|
| 296 |
+
chunk_start: bool
|
| 297 |
+
chunk_end: bool
|
| 298 |
+
|
| 299 |
+
def __init__(
|
| 300 |
+
self, data: bytes, chunk_start: bool = False, chunk_end: bool = False
|
| 301 |
+
) -> None:
|
| 302 |
+
object.__setattr__(self, "data", data)
|
| 303 |
+
object.__setattr__(self, "chunk_start", chunk_start)
|
| 304 |
+
object.__setattr__(self, "chunk_end", chunk_end)
|
| 305 |
+
|
| 306 |
+
# This is an unhashable type.
|
| 307 |
+
__hash__ = None # type: ignore
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
# XX FIXME: "A recipient MUST ignore (or consider as an error) any fields that
|
| 311 |
+
# are forbidden to be sent in a trailer, since processing them as if they were
|
| 312 |
+
# present in the header section might bypass external security filters."
|
| 313 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#chunked.trailer.part
|
| 314 |
+
# Unfortunately, the list of forbidden fields is long and vague :-/
|
| 315 |
+
@dataclass(init=False, frozen=True)
|
| 316 |
+
class EndOfMessage(Event):
|
| 317 |
+
"""The end of an HTTP message.
|
| 318 |
+
|
| 319 |
+
Fields:
|
| 320 |
+
|
| 321 |
+
.. attribute:: headers
|
| 322 |
+
|
| 323 |
+
Default value: ``[]``
|
| 324 |
+
|
| 325 |
+
Any trailing headers attached to this message, represented as a list of
|
| 326 |
+
(name, value) pairs. See :ref:`the header normalization rules
|
| 327 |
+
<headers-format>` for details.
|
| 328 |
+
|
| 329 |
+
Must be empty unless ``Transfer-Encoding: chunked`` is in use.
|
| 330 |
+
|
| 331 |
+
"""
|
| 332 |
+
|
| 333 |
+
__slots__ = ("headers",)
|
| 334 |
+
|
| 335 |
+
headers: Headers
|
| 336 |
+
|
| 337 |
+
def __init__(
|
| 338 |
+
self,
|
| 339 |
+
*,
|
| 340 |
+
headers: Union[
|
| 341 |
+
Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]], None
|
| 342 |
+
] = None,
|
| 343 |
+
_parsed: bool = False,
|
| 344 |
+
) -> None:
|
| 345 |
+
super().__init__()
|
| 346 |
+
if headers is None:
|
| 347 |
+
headers = Headers([])
|
| 348 |
+
elif not isinstance(headers, Headers):
|
| 349 |
+
headers = normalize_and_validate(headers, _parsed=_parsed)
|
| 350 |
+
|
| 351 |
+
object.__setattr__(self, "headers", headers)
|
| 352 |
+
|
| 353 |
+
# This is an unhashable type.
|
| 354 |
+
__hash__ = None # type: ignore
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
@dataclass(frozen=True)
|
| 358 |
+
class ConnectionClosed(Event):
|
| 359 |
+
"""This event indicates that the sender has closed their outgoing
|
| 360 |
+
connection.
|
| 361 |
+
|
| 362 |
+
Note that this does not necessarily mean that they can't *receive* further
|
| 363 |
+
data, because TCP connections are composed to two one-way channels which
|
| 364 |
+
can be closed independently. See :ref:`closing` for details.
|
| 365 |
+
|
| 366 |
+
No fields.
|
| 367 |
+
"""
|
| 368 |
+
|
| 369 |
+
pass
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_headers.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union
|
| 3 |
+
|
| 4 |
+
from ._abnf import field_name, field_value
|
| 5 |
+
from ._util import bytesify, LocalProtocolError, validate
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from ._events import Request
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
from typing import Literal
|
| 12 |
+
except ImportError:
|
| 13 |
+
from typing_extensions import Literal # type: ignore
|
| 14 |
+
|
| 15 |
+
CONTENT_LENGTH_MAX_DIGITS = 20 # allow up to 1 billion TB - 1
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# Facts
|
| 19 |
+
# -----
|
| 20 |
+
#
|
| 21 |
+
# Headers are:
|
| 22 |
+
# keys: case-insensitive ascii
|
| 23 |
+
# values: mixture of ascii and raw bytes
|
| 24 |
+
#
|
| 25 |
+
# "Historically, HTTP has allowed field content with text in the ISO-8859-1
|
| 26 |
+
# charset [ISO-8859-1], supporting other charsets only through use of
|
| 27 |
+
# [RFC2047] encoding. In practice, most HTTP header field values use only a
|
| 28 |
+
# subset of the US-ASCII charset [USASCII]. Newly defined header fields SHOULD
|
| 29 |
+
# limit their field values to US-ASCII octets. A recipient SHOULD treat other
|
| 30 |
+
# octets in field content (obs-text) as opaque data."
|
| 31 |
+
# And it deprecates all non-ascii values
|
| 32 |
+
#
|
| 33 |
+
# Leading/trailing whitespace in header names is forbidden
|
| 34 |
+
#
|
| 35 |
+
# Values get leading/trailing whitespace stripped
|
| 36 |
+
#
|
| 37 |
+
# Content-Disposition actually needs to contain unicode semantically; to
|
| 38 |
+
# accomplish this it has a terrifically weird way of encoding the filename
|
| 39 |
+
# itself as ascii (and even this still has lots of cross-browser
|
| 40 |
+
# incompatibilities)
|
| 41 |
+
#
|
| 42 |
+
# Order is important:
|
| 43 |
+
# "a proxy MUST NOT change the order of these field values when forwarding a
|
| 44 |
+
# message"
|
| 45 |
+
# (and there are several headers where the order indicates a preference)
|
| 46 |
+
#
|
| 47 |
+
# Multiple occurences of the same header:
|
| 48 |
+
# "A sender MUST NOT generate multiple header fields with the same field name
|
| 49 |
+
# in a message unless either the entire field value for that header field is
|
| 50 |
+
# defined as a comma-separated list [or the header is Set-Cookie which gets a
|
| 51 |
+
# special exception]" - RFC 7230. (cookies are in RFC 6265)
|
| 52 |
+
#
|
| 53 |
+
# So every header aside from Set-Cookie can be merged by b", ".join if it
|
| 54 |
+
# occurs repeatedly. But, of course, they can't necessarily be split by
|
| 55 |
+
# .split(b","), because quoting.
|
| 56 |
+
#
|
| 57 |
+
# Given all this mess (case insensitive, duplicates allowed, order is
|
| 58 |
+
# important, ...), there doesn't appear to be any standard way to handle
|
| 59 |
+
# headers in Python -- they're almost like dicts, but... actually just
|
| 60 |
+
# aren't. For now we punt and just use a super simple representation: headers
|
| 61 |
+
# are a list of pairs
|
| 62 |
+
#
|
| 63 |
+
# [(name1, value1), (name2, value2), ...]
|
| 64 |
+
#
|
| 65 |
+
# where all entries are bytestrings, names are lowercase and have no
|
| 66 |
+
# leading/trailing whitespace, and values are bytestrings with no
|
| 67 |
+
# leading/trailing whitespace. Searching and updating are done via naive O(n)
|
| 68 |
+
# methods.
|
| 69 |
+
#
|
| 70 |
+
# Maybe a dict-of-lists would be better?
|
| 71 |
+
|
| 72 |
+
_content_length_re = re.compile(rb"[0-9]+")
|
| 73 |
+
_field_name_re = re.compile(field_name.encode("ascii"))
|
| 74 |
+
_field_value_re = re.compile(field_value.encode("ascii"))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class Headers(Sequence[Tuple[bytes, bytes]]):
|
| 78 |
+
"""
|
| 79 |
+
A list-like interface that allows iterating over headers as byte-pairs
|
| 80 |
+
of (lowercased-name, value).
|
| 81 |
+
|
| 82 |
+
Internally we actually store the representation as three-tuples,
|
| 83 |
+
including both the raw original casing, in order to preserve casing
|
| 84 |
+
over-the-wire, and the lowercased name, for case-insensitive comparisions.
|
| 85 |
+
|
| 86 |
+
r = Request(
|
| 87 |
+
method="GET",
|
| 88 |
+
target="/",
|
| 89 |
+
headers=[("Host", "example.org"), ("Connection", "keep-alive")],
|
| 90 |
+
http_version="1.1",
|
| 91 |
+
)
|
| 92 |
+
assert r.headers == [
|
| 93 |
+
(b"host", b"example.org"),
|
| 94 |
+
(b"connection", b"keep-alive")
|
| 95 |
+
]
|
| 96 |
+
assert r.headers.raw_items() == [
|
| 97 |
+
(b"Host", b"example.org"),
|
| 98 |
+
(b"Connection", b"keep-alive")
|
| 99 |
+
]
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
__slots__ = "_full_items"
|
| 103 |
+
|
| 104 |
+
def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None:
|
| 105 |
+
self._full_items = full_items
|
| 106 |
+
|
| 107 |
+
def __bool__(self) -> bool:
|
| 108 |
+
return bool(self._full_items)
|
| 109 |
+
|
| 110 |
+
def __eq__(self, other: object) -> bool:
|
| 111 |
+
return list(self) == list(other) # type: ignore
|
| 112 |
+
|
| 113 |
+
def __len__(self) -> int:
|
| 114 |
+
return len(self._full_items)
|
| 115 |
+
|
| 116 |
+
def __repr__(self) -> str:
|
| 117 |
+
return "<Headers(%s)>" % repr(list(self))
|
| 118 |
+
|
| 119 |
+
def __getitem__(self, idx: int) -> Tuple[bytes, bytes]: # type: ignore[override]
|
| 120 |
+
_, name, value = self._full_items[idx]
|
| 121 |
+
return (name, value)
|
| 122 |
+
|
| 123 |
+
def raw_items(self) -> List[Tuple[bytes, bytes]]:
|
| 124 |
+
return [(raw_name, value) for raw_name, _, value in self._full_items]
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
HeaderTypes = Union[
|
| 128 |
+
List[Tuple[bytes, bytes]],
|
| 129 |
+
List[Tuple[bytes, str]],
|
| 130 |
+
List[Tuple[str, bytes]],
|
| 131 |
+
List[Tuple[str, str]],
|
| 132 |
+
]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@overload
|
| 136 |
+
def normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers:
|
| 137 |
+
...
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@overload
|
| 141 |
+
def normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers:
|
| 142 |
+
...
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@overload
|
| 146 |
+
def normalize_and_validate(
|
| 147 |
+
headers: Union[Headers, HeaderTypes], _parsed: bool = False
|
| 148 |
+
) -> Headers:
|
| 149 |
+
...
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def normalize_and_validate(
|
| 153 |
+
headers: Union[Headers, HeaderTypes], _parsed: bool = False
|
| 154 |
+
) -> Headers:
|
| 155 |
+
new_headers = []
|
| 156 |
+
seen_content_length = None
|
| 157 |
+
saw_transfer_encoding = False
|
| 158 |
+
for name, value in headers:
|
| 159 |
+
# For headers coming out of the parser, we can safely skip some steps,
|
| 160 |
+
# because it always returns bytes and has already run these regexes
|
| 161 |
+
# over the data:
|
| 162 |
+
if not _parsed:
|
| 163 |
+
name = bytesify(name)
|
| 164 |
+
value = bytesify(value)
|
| 165 |
+
validate(_field_name_re, name, "Illegal header name {!r}", name)
|
| 166 |
+
validate(_field_value_re, value, "Illegal header value {!r}", value)
|
| 167 |
+
assert isinstance(name, bytes)
|
| 168 |
+
assert isinstance(value, bytes)
|
| 169 |
+
|
| 170 |
+
raw_name = name
|
| 171 |
+
name = name.lower()
|
| 172 |
+
if name == b"content-length":
|
| 173 |
+
lengths = {length.strip() for length in value.split(b",")}
|
| 174 |
+
if len(lengths) != 1:
|
| 175 |
+
raise LocalProtocolError("conflicting Content-Length headers")
|
| 176 |
+
value = lengths.pop()
|
| 177 |
+
validate(_content_length_re, value, "bad Content-Length")
|
| 178 |
+
if len(value) > CONTENT_LENGTH_MAX_DIGITS:
|
| 179 |
+
raise LocalProtocolError("bad Content-Length")
|
| 180 |
+
if seen_content_length is None:
|
| 181 |
+
seen_content_length = value
|
| 182 |
+
new_headers.append((raw_name, name, value))
|
| 183 |
+
elif seen_content_length != value:
|
| 184 |
+
raise LocalProtocolError("conflicting Content-Length headers")
|
| 185 |
+
elif name == b"transfer-encoding":
|
| 186 |
+
# "A server that receives a request message with a transfer coding
|
| 187 |
+
# it does not understand SHOULD respond with 501 (Not
|
| 188 |
+
# Implemented)."
|
| 189 |
+
# https://tools.ietf.org/html/rfc7230#section-3.3.1
|
| 190 |
+
if saw_transfer_encoding:
|
| 191 |
+
raise LocalProtocolError(
|
| 192 |
+
"multiple Transfer-Encoding headers", error_status_hint=501
|
| 193 |
+
)
|
| 194 |
+
# "All transfer-coding names are case-insensitive"
|
| 195 |
+
# -- https://tools.ietf.org/html/rfc7230#section-4
|
| 196 |
+
value = value.lower()
|
| 197 |
+
if value != b"chunked":
|
| 198 |
+
raise LocalProtocolError(
|
| 199 |
+
"Only Transfer-Encoding: chunked is supported",
|
| 200 |
+
error_status_hint=501,
|
| 201 |
+
)
|
| 202 |
+
saw_transfer_encoding = True
|
| 203 |
+
new_headers.append((raw_name, name, value))
|
| 204 |
+
else:
|
| 205 |
+
new_headers.append((raw_name, name, value))
|
| 206 |
+
return Headers(new_headers)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def get_comma_header(headers: Headers, name: bytes) -> List[bytes]:
|
| 210 |
+
# Should only be used for headers whose value is a list of
|
| 211 |
+
# comma-separated, case-insensitive values.
|
| 212 |
+
#
|
| 213 |
+
# The header name `name` is expected to be lower-case bytes.
|
| 214 |
+
#
|
| 215 |
+
# Connection: meets these criteria (including cast insensitivity).
|
| 216 |
+
#
|
| 217 |
+
# Content-Length: technically is just a single value (1*DIGIT), but the
|
| 218 |
+
# standard makes reference to implementations that do multiple values, and
|
| 219 |
+
# using this doesn't hurt. Ditto, case insensitivity doesn't things either
|
| 220 |
+
# way.
|
| 221 |
+
#
|
| 222 |
+
# Transfer-Encoding: is more complex (allows for quoted strings), so
|
| 223 |
+
# splitting on , is actually wrong. For example, this is legal:
|
| 224 |
+
#
|
| 225 |
+
# Transfer-Encoding: foo; options="1,2", chunked
|
| 226 |
+
#
|
| 227 |
+
# and should be parsed as
|
| 228 |
+
#
|
| 229 |
+
# foo; options="1,2"
|
| 230 |
+
# chunked
|
| 231 |
+
#
|
| 232 |
+
# but this naive function will parse it as
|
| 233 |
+
#
|
| 234 |
+
# foo; options="1
|
| 235 |
+
# 2"
|
| 236 |
+
# chunked
|
| 237 |
+
#
|
| 238 |
+
# However, this is okay because the only thing we are going to do with
|
| 239 |
+
# any Transfer-Encoding is reject ones that aren't just "chunked", so
|
| 240 |
+
# both of these will be treated the same anyway.
|
| 241 |
+
#
|
| 242 |
+
# Expect: the only legal value is the literal string
|
| 243 |
+
# "100-continue". Splitting on commas is harmless. Case insensitive.
|
| 244 |
+
#
|
| 245 |
+
out: List[bytes] = []
|
| 246 |
+
for _, found_name, found_raw_value in headers._full_items:
|
| 247 |
+
if found_name == name:
|
| 248 |
+
found_raw_value = found_raw_value.lower()
|
| 249 |
+
for found_split_value in found_raw_value.split(b","):
|
| 250 |
+
found_split_value = found_split_value.strip()
|
| 251 |
+
if found_split_value:
|
| 252 |
+
out.append(found_split_value)
|
| 253 |
+
return out
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def set_comma_header(headers: Headers, name: bytes, new_values: List[bytes]) -> Headers:
|
| 257 |
+
# The header name `name` is expected to be lower-case bytes.
|
| 258 |
+
#
|
| 259 |
+
# Note that when we store the header we use title casing for the header
|
| 260 |
+
# names, in order to match the conventional HTTP header style.
|
| 261 |
+
#
|
| 262 |
+
# Simply calling `.title()` is a blunt approach, but it's correct
|
| 263 |
+
# here given the cases where we're using `set_comma_header`...
|
| 264 |
+
#
|
| 265 |
+
# Connection, Content-Length, Transfer-Encoding.
|
| 266 |
+
new_headers: List[Tuple[bytes, bytes]] = []
|
| 267 |
+
for found_raw_name, found_name, found_raw_value in headers._full_items:
|
| 268 |
+
if found_name != name:
|
| 269 |
+
new_headers.append((found_raw_name, found_raw_value))
|
| 270 |
+
for new_value in new_values:
|
| 271 |
+
new_headers.append((name.title(), new_value))
|
| 272 |
+
return normalize_and_validate(new_headers)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def has_expect_100_continue(request: "Request") -> bool:
|
| 276 |
+
# https://tools.ietf.org/html/rfc7231#section-5.1.1
|
| 277 |
+
# "A server that receives a 100-continue expectation in an HTTP/1.0 request
|
| 278 |
+
# MUST ignore that expectation."
|
| 279 |
+
if request.http_version < b"1.1":
|
| 280 |
+
return False
|
| 281 |
+
expect = get_comma_header(request.headers, b"expect")
|
| 282 |
+
return b"100-continue" in expect
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_readers.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Code to read HTTP data
|
| 2 |
+
#
|
| 3 |
+
# Strategy: each reader is a callable which takes a ReceiveBuffer object, and
|
| 4 |
+
# either:
|
| 5 |
+
# 1) consumes some of it and returns an Event
|
| 6 |
+
# 2) raises a LocalProtocolError (for consistency -- e.g. we call validate()
|
| 7 |
+
# and it might raise a LocalProtocolError, so simpler just to always use
|
| 8 |
+
# this)
|
| 9 |
+
# 3) returns None, meaning "I need more data"
|
| 10 |
+
#
|
| 11 |
+
# If they have a .read_eof attribute, then this will be called if an EOF is
|
| 12 |
+
# received -- but this is optional. Either way, the actual ConnectionClosed
|
| 13 |
+
# event will be generated afterwards.
|
| 14 |
+
#
|
| 15 |
+
# READERS is a dict describing how to pick a reader. It maps states to either:
|
| 16 |
+
# - a reader
|
| 17 |
+
# - or, for body readers, a dict of per-framing reader factories
|
| 18 |
+
|
| 19 |
+
import re
|
| 20 |
+
from typing import Any, Callable, Dict, Iterable, NoReturn, Optional, Tuple, Type, Union
|
| 21 |
+
|
| 22 |
+
from ._abnf import chunk_header, header_field, request_line, status_line
|
| 23 |
+
from ._events import Data, EndOfMessage, InformationalResponse, Request, Response
|
| 24 |
+
from ._receivebuffer import ReceiveBuffer
|
| 25 |
+
from ._state import (
|
| 26 |
+
CLIENT,
|
| 27 |
+
CLOSED,
|
| 28 |
+
DONE,
|
| 29 |
+
IDLE,
|
| 30 |
+
MUST_CLOSE,
|
| 31 |
+
SEND_BODY,
|
| 32 |
+
SEND_RESPONSE,
|
| 33 |
+
SERVER,
|
| 34 |
+
)
|
| 35 |
+
from ._util import LocalProtocolError, RemoteProtocolError, Sentinel, validate
|
| 36 |
+
|
| 37 |
+
__all__ = ["READERS"]
|
| 38 |
+
|
| 39 |
+
header_field_re = re.compile(header_field.encode("ascii"))
|
| 40 |
+
obs_fold_re = re.compile(rb"[ \t]+")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _obsolete_line_fold(lines: Iterable[bytes]) -> Iterable[bytes]:
|
| 44 |
+
it = iter(lines)
|
| 45 |
+
last: Optional[bytes] = None
|
| 46 |
+
for line in it:
|
| 47 |
+
match = obs_fold_re.match(line)
|
| 48 |
+
if match:
|
| 49 |
+
if last is None:
|
| 50 |
+
raise LocalProtocolError("continuation line at start of headers")
|
| 51 |
+
if not isinstance(last, bytearray):
|
| 52 |
+
# Cast to a mutable type, avoiding copy on append to ensure O(n) time
|
| 53 |
+
last = bytearray(last)
|
| 54 |
+
last += b" "
|
| 55 |
+
last += line[match.end() :]
|
| 56 |
+
else:
|
| 57 |
+
if last is not None:
|
| 58 |
+
yield last
|
| 59 |
+
last = line
|
| 60 |
+
if last is not None:
|
| 61 |
+
yield last
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _decode_header_lines(
|
| 65 |
+
lines: Iterable[bytes],
|
| 66 |
+
) -> Iterable[Tuple[bytes, bytes]]:
|
| 67 |
+
for line in _obsolete_line_fold(lines):
|
| 68 |
+
matches = validate(header_field_re, line, "illegal header line: {!r}", line)
|
| 69 |
+
yield (matches["field_name"], matches["field_value"])
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
request_line_re = re.compile(request_line.encode("ascii"))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def maybe_read_from_IDLE_client(buf: ReceiveBuffer) -> Optional[Request]:
|
| 76 |
+
lines = buf.maybe_extract_lines()
|
| 77 |
+
if lines is None:
|
| 78 |
+
if buf.is_next_line_obviously_invalid_request_line():
|
| 79 |
+
raise LocalProtocolError("illegal request line")
|
| 80 |
+
return None
|
| 81 |
+
if not lines:
|
| 82 |
+
raise LocalProtocolError("no request line received")
|
| 83 |
+
matches = validate(
|
| 84 |
+
request_line_re, lines[0], "illegal request line: {!r}", lines[0]
|
| 85 |
+
)
|
| 86 |
+
return Request(
|
| 87 |
+
headers=list(_decode_header_lines(lines[1:])), _parsed=True, **matches
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
status_line_re = re.compile(status_line.encode("ascii"))
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def maybe_read_from_SEND_RESPONSE_server(
|
| 95 |
+
buf: ReceiveBuffer,
|
| 96 |
+
) -> Union[InformationalResponse, Response, None]:
|
| 97 |
+
lines = buf.maybe_extract_lines()
|
| 98 |
+
if lines is None:
|
| 99 |
+
if buf.is_next_line_obviously_invalid_request_line():
|
| 100 |
+
raise LocalProtocolError("illegal request line")
|
| 101 |
+
return None
|
| 102 |
+
if not lines:
|
| 103 |
+
raise LocalProtocolError("no response line received")
|
| 104 |
+
matches = validate(status_line_re, lines[0], "illegal status line: {!r}", lines[0])
|
| 105 |
+
http_version = (
|
| 106 |
+
b"1.1" if matches["http_version"] is None else matches["http_version"]
|
| 107 |
+
)
|
| 108 |
+
reason = b"" if matches["reason"] is None else matches["reason"]
|
| 109 |
+
status_code = int(matches["status_code"])
|
| 110 |
+
class_: Union[Type[InformationalResponse], Type[Response]] = (
|
| 111 |
+
InformationalResponse if status_code < 200 else Response
|
| 112 |
+
)
|
| 113 |
+
return class_(
|
| 114 |
+
headers=list(_decode_header_lines(lines[1:])),
|
| 115 |
+
_parsed=True,
|
| 116 |
+
status_code=status_code,
|
| 117 |
+
reason=reason,
|
| 118 |
+
http_version=http_version,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class ContentLengthReader:
|
| 123 |
+
def __init__(self, length: int) -> None:
|
| 124 |
+
self._length = length
|
| 125 |
+
self._remaining = length
|
| 126 |
+
|
| 127 |
+
def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]:
|
| 128 |
+
if self._remaining == 0:
|
| 129 |
+
return EndOfMessage()
|
| 130 |
+
data = buf.maybe_extract_at_most(self._remaining)
|
| 131 |
+
if data is None:
|
| 132 |
+
return None
|
| 133 |
+
self._remaining -= len(data)
|
| 134 |
+
return Data(data=data)
|
| 135 |
+
|
| 136 |
+
def read_eof(self) -> NoReturn:
|
| 137 |
+
raise RemoteProtocolError(
|
| 138 |
+
"peer closed connection without sending complete message body "
|
| 139 |
+
"(received {} bytes, expected {})".format(
|
| 140 |
+
self._length - self._remaining, self._length
|
| 141 |
+
)
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
chunk_header_re = re.compile(chunk_header.encode("ascii"))
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class ChunkedReader:
|
| 149 |
+
def __init__(self) -> None:
|
| 150 |
+
self._bytes_in_chunk = 0
|
| 151 |
+
# After reading a chunk, we have to throw away the trailing \r\n.
|
| 152 |
+
# This tracks the bytes that we need to match and throw away.
|
| 153 |
+
self._bytes_to_discard = b""
|
| 154 |
+
self._reading_trailer = False
|
| 155 |
+
|
| 156 |
+
def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]:
|
| 157 |
+
if self._reading_trailer:
|
| 158 |
+
lines = buf.maybe_extract_lines()
|
| 159 |
+
if lines is None:
|
| 160 |
+
return None
|
| 161 |
+
return EndOfMessage(headers=list(_decode_header_lines(lines)))
|
| 162 |
+
if self._bytes_to_discard:
|
| 163 |
+
data = buf.maybe_extract_at_most(len(self._bytes_to_discard))
|
| 164 |
+
if data is None:
|
| 165 |
+
return None
|
| 166 |
+
if data != self._bytes_to_discard[: len(data)]:
|
| 167 |
+
raise LocalProtocolError(
|
| 168 |
+
f"malformed chunk footer: {data!r} (expected {self._bytes_to_discard!r})"
|
| 169 |
+
)
|
| 170 |
+
self._bytes_to_discard = self._bytes_to_discard[len(data) :]
|
| 171 |
+
if self._bytes_to_discard:
|
| 172 |
+
return None
|
| 173 |
+
# else, fall through and read some more
|
| 174 |
+
assert self._bytes_to_discard == b""
|
| 175 |
+
if self._bytes_in_chunk == 0:
|
| 176 |
+
# We need to refill our chunk count
|
| 177 |
+
chunk_header = buf.maybe_extract_next_line()
|
| 178 |
+
if chunk_header is None:
|
| 179 |
+
return None
|
| 180 |
+
matches = validate(
|
| 181 |
+
chunk_header_re,
|
| 182 |
+
chunk_header,
|
| 183 |
+
"illegal chunk header: {!r}",
|
| 184 |
+
chunk_header,
|
| 185 |
+
)
|
| 186 |
+
# XX FIXME: we discard chunk extensions. Does anyone care?
|
| 187 |
+
self._bytes_in_chunk = int(matches["chunk_size"], base=16)
|
| 188 |
+
if self._bytes_in_chunk == 0:
|
| 189 |
+
self._reading_trailer = True
|
| 190 |
+
return self(buf)
|
| 191 |
+
chunk_start = True
|
| 192 |
+
else:
|
| 193 |
+
chunk_start = False
|
| 194 |
+
assert self._bytes_in_chunk > 0
|
| 195 |
+
data = buf.maybe_extract_at_most(self._bytes_in_chunk)
|
| 196 |
+
if data is None:
|
| 197 |
+
return None
|
| 198 |
+
self._bytes_in_chunk -= len(data)
|
| 199 |
+
if self._bytes_in_chunk == 0:
|
| 200 |
+
self._bytes_to_discard = b"\r\n"
|
| 201 |
+
chunk_end = True
|
| 202 |
+
else:
|
| 203 |
+
chunk_end = False
|
| 204 |
+
return Data(data=data, chunk_start=chunk_start, chunk_end=chunk_end)
|
| 205 |
+
|
| 206 |
+
def read_eof(self) -> NoReturn:
|
| 207 |
+
raise RemoteProtocolError(
|
| 208 |
+
"peer closed connection without sending complete message body "
|
| 209 |
+
"(incomplete chunked read)"
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class Http10Reader:
|
| 214 |
+
def __call__(self, buf: ReceiveBuffer) -> Optional[Data]:
|
| 215 |
+
data = buf.maybe_extract_at_most(999999999)
|
| 216 |
+
if data is None:
|
| 217 |
+
return None
|
| 218 |
+
return Data(data=data)
|
| 219 |
+
|
| 220 |
+
def read_eof(self) -> EndOfMessage:
|
| 221 |
+
return EndOfMessage()
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def expect_nothing(buf: ReceiveBuffer) -> None:
|
| 225 |
+
if buf:
|
| 226 |
+
raise LocalProtocolError("Got data when expecting EOF")
|
| 227 |
+
return None
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
ReadersType = Dict[
|
| 231 |
+
Union[Type[Sentinel], Tuple[Type[Sentinel], Type[Sentinel]]],
|
| 232 |
+
Union[Callable[..., Any], Dict[str, Callable[..., Any]]],
|
| 233 |
+
]
|
| 234 |
+
|
| 235 |
+
READERS: ReadersType = {
|
| 236 |
+
(CLIENT, IDLE): maybe_read_from_IDLE_client,
|
| 237 |
+
(SERVER, IDLE): maybe_read_from_SEND_RESPONSE_server,
|
| 238 |
+
(SERVER, SEND_RESPONSE): maybe_read_from_SEND_RESPONSE_server,
|
| 239 |
+
(CLIENT, DONE): expect_nothing,
|
| 240 |
+
(CLIENT, MUST_CLOSE): expect_nothing,
|
| 241 |
+
(CLIENT, CLOSED): expect_nothing,
|
| 242 |
+
(SERVER, DONE): expect_nothing,
|
| 243 |
+
(SERVER, MUST_CLOSE): expect_nothing,
|
| 244 |
+
(SERVER, CLOSED): expect_nothing,
|
| 245 |
+
SEND_BODY: {
|
| 246 |
+
"chunked": ChunkedReader,
|
| 247 |
+
"content-length": ContentLengthReader,
|
| 248 |
+
"http/1.0": Http10Reader,
|
| 249 |
+
},
|
| 250 |
+
}
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_receivebuffer.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import sys
|
| 3 |
+
from typing import List, Optional, Union
|
| 4 |
+
|
| 5 |
+
__all__ = ["ReceiveBuffer"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# Operations we want to support:
|
| 9 |
+
# - find next \r\n or \r\n\r\n (\n or \n\n are also acceptable),
|
| 10 |
+
# or wait until there is one
|
| 11 |
+
# - read at-most-N bytes
|
| 12 |
+
# Goals:
|
| 13 |
+
# - on average, do this fast
|
| 14 |
+
# - worst case, do this in O(n) where n is the number of bytes processed
|
| 15 |
+
# Plan:
|
| 16 |
+
# - store bytearray, offset, how far we've searched for a separator token
|
| 17 |
+
# - use the how-far-we've-searched data to avoid rescanning
|
| 18 |
+
# - while doing a stream of uninterrupted processing, advance offset instead
|
| 19 |
+
# of constantly copying
|
| 20 |
+
# WARNING:
|
| 21 |
+
# - I haven't benchmarked or profiled any of this yet.
|
| 22 |
+
#
|
| 23 |
+
# Note that starting in Python 3.4, deleting the initial n bytes from a
|
| 24 |
+
# bytearray is amortized O(n), thanks to some excellent work by Antoine
|
| 25 |
+
# Martin:
|
| 26 |
+
#
|
| 27 |
+
# https://bugs.python.org/issue19087
|
| 28 |
+
#
|
| 29 |
+
# This means that if we only supported 3.4+, we could get rid of the code here
|
| 30 |
+
# involving self._start and self.compress, because it's doing exactly the same
|
| 31 |
+
# thing that bytearray now does internally.
|
| 32 |
+
#
|
| 33 |
+
# BUT unfortunately, we still support 2.7, and reading short segments out of a
|
| 34 |
+
# long buffer MUST be O(bytes read) to avoid DoS issues, so we can't actually
|
| 35 |
+
# delete this code. Yet:
|
| 36 |
+
#
|
| 37 |
+
# https://pythonclock.org/
|
| 38 |
+
#
|
| 39 |
+
# (Two things to double-check first though: make sure PyPy also has the
|
| 40 |
+
# optimization, and benchmark to make sure it's a win, since we do have a
|
| 41 |
+
# slightly clever thing where we delay calling compress() until we've
|
| 42 |
+
# processed a whole event, which could in theory be slightly more efficient
|
| 43 |
+
# than the internal bytearray support.)
|
| 44 |
+
blank_line_regex = re.compile(b"\n\r?\n", re.MULTILINE)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class ReceiveBuffer:
|
| 48 |
+
def __init__(self) -> None:
|
| 49 |
+
self._data = bytearray()
|
| 50 |
+
self._next_line_search = 0
|
| 51 |
+
self._multiple_lines_search = 0
|
| 52 |
+
|
| 53 |
+
def __iadd__(self, byteslike: Union[bytes, bytearray]) -> "ReceiveBuffer":
|
| 54 |
+
self._data += byteslike
|
| 55 |
+
return self
|
| 56 |
+
|
| 57 |
+
def __bool__(self) -> bool:
|
| 58 |
+
return bool(len(self))
|
| 59 |
+
|
| 60 |
+
def __len__(self) -> int:
|
| 61 |
+
return len(self._data)
|
| 62 |
+
|
| 63 |
+
# for @property unprocessed_data
|
| 64 |
+
def __bytes__(self) -> bytes:
|
| 65 |
+
return bytes(self._data)
|
| 66 |
+
|
| 67 |
+
def _extract(self, count: int) -> bytearray:
|
| 68 |
+
# extracting an initial slice of the data buffer and return it
|
| 69 |
+
out = self._data[:count]
|
| 70 |
+
del self._data[:count]
|
| 71 |
+
|
| 72 |
+
self._next_line_search = 0
|
| 73 |
+
self._multiple_lines_search = 0
|
| 74 |
+
|
| 75 |
+
return out
|
| 76 |
+
|
| 77 |
+
def maybe_extract_at_most(self, count: int) -> Optional[bytearray]:
|
| 78 |
+
"""
|
| 79 |
+
Extract a fixed number of bytes from the buffer.
|
| 80 |
+
"""
|
| 81 |
+
out = self._data[:count]
|
| 82 |
+
if not out:
|
| 83 |
+
return None
|
| 84 |
+
|
| 85 |
+
return self._extract(count)
|
| 86 |
+
|
| 87 |
+
def maybe_extract_next_line(self) -> Optional[bytearray]:
|
| 88 |
+
"""
|
| 89 |
+
Extract the first line, if it is completed in the buffer.
|
| 90 |
+
"""
|
| 91 |
+
# Only search in buffer space that we've not already looked at.
|
| 92 |
+
search_start_index = max(0, self._next_line_search - 1)
|
| 93 |
+
partial_idx = self._data.find(b"\r\n", search_start_index)
|
| 94 |
+
|
| 95 |
+
if partial_idx == -1:
|
| 96 |
+
self._next_line_search = len(self._data)
|
| 97 |
+
return None
|
| 98 |
+
|
| 99 |
+
# + 2 is to compensate len(b"\r\n")
|
| 100 |
+
idx = partial_idx + 2
|
| 101 |
+
|
| 102 |
+
return self._extract(idx)
|
| 103 |
+
|
| 104 |
+
def maybe_extract_lines(self) -> Optional[List[bytearray]]:
|
| 105 |
+
"""
|
| 106 |
+
Extract everything up to the first blank line, and return a list of lines.
|
| 107 |
+
"""
|
| 108 |
+
# Handle the case where we have an immediate empty line.
|
| 109 |
+
if self._data[:1] == b"\n":
|
| 110 |
+
self._extract(1)
|
| 111 |
+
return []
|
| 112 |
+
|
| 113 |
+
if self._data[:2] == b"\r\n":
|
| 114 |
+
self._extract(2)
|
| 115 |
+
return []
|
| 116 |
+
|
| 117 |
+
# Only search in buffer space that we've not already looked at.
|
| 118 |
+
match = blank_line_regex.search(self._data, self._multiple_lines_search)
|
| 119 |
+
if match is None:
|
| 120 |
+
self._multiple_lines_search = max(0, len(self._data) - 2)
|
| 121 |
+
return None
|
| 122 |
+
|
| 123 |
+
# Truncate the buffer and return it.
|
| 124 |
+
idx = match.span(0)[-1]
|
| 125 |
+
out = self._extract(idx)
|
| 126 |
+
lines = out.split(b"\n")
|
| 127 |
+
|
| 128 |
+
for line in lines:
|
| 129 |
+
if line.endswith(b"\r"):
|
| 130 |
+
del line[-1]
|
| 131 |
+
|
| 132 |
+
assert lines[-2] == lines[-1] == b""
|
| 133 |
+
|
| 134 |
+
del lines[-2:]
|
| 135 |
+
|
| 136 |
+
return lines
|
| 137 |
+
|
| 138 |
+
# In theory we should wait until `\r\n` before starting to validate
|
| 139 |
+
# incoming data. However it's interesting to detect (very) invalid data
|
| 140 |
+
# early given they might not even contain `\r\n` at all (hence only
|
| 141 |
+
# timeout will get rid of them).
|
| 142 |
+
# This is not a 100% effective detection but more of a cheap sanity check
|
| 143 |
+
# allowing for early abort in some useful cases.
|
| 144 |
+
# This is especially interesting when peer is messing up with HTTPS and
|
| 145 |
+
# sent us a TLS stream where we were expecting plain HTTP given all
|
| 146 |
+
# versions of TLS so far start handshake with a 0x16 message type code.
|
| 147 |
+
def is_next_line_obviously_invalid_request_line(self) -> bool:
|
| 148 |
+
try:
|
| 149 |
+
# HTTP header line must not contain non-printable characters
|
| 150 |
+
# and should not start with a space
|
| 151 |
+
return self._data[0] < 0x21
|
| 152 |
+
except IndexError:
|
| 153 |
+
return False
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_state.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
| 1 |
+
################################################################
|
| 2 |
+
# The core state machine
|
| 3 |
+
################################################################
|
| 4 |
+
#
|
| 5 |
+
# Rule 1: everything that affects the state machine and state transitions must
|
| 6 |
+
# live here in this file. As much as possible goes into the table-based
|
| 7 |
+
# representation, but for the bits that don't quite fit, the actual code and
|
| 8 |
+
# state must nonetheless live here.
|
| 9 |
+
#
|
| 10 |
+
# Rule 2: this file does not know about what role we're playing; it only knows
|
| 11 |
+
# about HTTP request/response cycles in the abstract. This ensures that we
|
| 12 |
+
# don't cheat and apply different rules to local and remote parties.
|
| 13 |
+
#
|
| 14 |
+
#
|
| 15 |
+
# Theory of operation
|
| 16 |
+
# ===================
|
| 17 |
+
#
|
| 18 |
+
# Possibly the simplest way to think about this is that we actually have 5
|
| 19 |
+
# different state machines here. Yes, 5. These are:
|
| 20 |
+
#
|
| 21 |
+
# 1) The client state, with its complicated automaton (see the docs)
|
| 22 |
+
# 2) The server state, with its complicated automaton (see the docs)
|
| 23 |
+
# 3) The keep-alive state, with possible states {True, False}
|
| 24 |
+
# 4) The SWITCH_CONNECT state, with possible states {False, True}
|
| 25 |
+
# 5) The SWITCH_UPGRADE state, with possible states {False, True}
|
| 26 |
+
#
|
| 27 |
+
# For (3)-(5), the first state listed is the initial state.
|
| 28 |
+
#
|
| 29 |
+
# (1)-(3) are stored explicitly in member variables. The last
|
| 30 |
+
# two are stored implicitly in the pending_switch_proposals set as:
|
| 31 |
+
# (state of 4) == (_SWITCH_CONNECT in pending_switch_proposals)
|
| 32 |
+
# (state of 5) == (_SWITCH_UPGRADE in pending_switch_proposals)
|
| 33 |
+
#
|
| 34 |
+
# And each of these machines has two different kinds of transitions:
|
| 35 |
+
#
|
| 36 |
+
# a) Event-triggered
|
| 37 |
+
# b) State-triggered
|
| 38 |
+
#
|
| 39 |
+
# Event triggered is the obvious thing that you'd think it is: some event
|
| 40 |
+
# happens, and if it's the right event at the right time then a transition
|
| 41 |
+
# happens. But there are somewhat complicated rules for which machines can
|
| 42 |
+
# "see" which events. (As a rule of thumb, if a machine "sees" an event, this
|
| 43 |
+
# means two things: the event can affect the machine, and if the machine is
|
| 44 |
+
# not in a state where it expects that event then it's an error.) These rules
|
| 45 |
+
# are:
|
| 46 |
+
#
|
| 47 |
+
# 1) The client machine sees all h11.events objects emitted by the client.
|
| 48 |
+
#
|
| 49 |
+
# 2) The server machine sees all h11.events objects emitted by the server.
|
| 50 |
+
#
|
| 51 |
+
# It also sees the client's Request event.
|
| 52 |
+
#
|
| 53 |
+
# And sometimes, server events are annotated with a _SWITCH_* event. For
|
| 54 |
+
# example, we can have a (Response, _SWITCH_CONNECT) event, which is
|
| 55 |
+
# different from a regular Response event.
|
| 56 |
+
#
|
| 57 |
+
# 3) The keep-alive machine sees the process_keep_alive_disabled() event
|
| 58 |
+
# (which is derived from Request/Response events), and this event
|
| 59 |
+
# transitions it from True -> False, or from False -> False. There's no way
|
| 60 |
+
# to transition back.
|
| 61 |
+
#
|
| 62 |
+
# 4&5) The _SWITCH_* machines transition from False->True when we get a
|
| 63 |
+
# Request that proposes the relevant type of switch (via
|
| 64 |
+
# process_client_switch_proposals), and they go from True->False when we
|
| 65 |
+
# get a Response that has no _SWITCH_* annotation.
|
| 66 |
+
#
|
| 67 |
+
# So that's event-triggered transitions.
|
| 68 |
+
#
|
| 69 |
+
# State-triggered transitions are less standard. What they do here is couple
|
| 70 |
+
# the machines together. The way this works is, when certain *joint*
|
| 71 |
+
# configurations of states are achieved, then we automatically transition to a
|
| 72 |
+
# new *joint* state. So, for example, if we're ever in a joint state with
|
| 73 |
+
#
|
| 74 |
+
# client: DONE
|
| 75 |
+
# keep-alive: False
|
| 76 |
+
#
|
| 77 |
+
# then the client state immediately transitions to:
|
| 78 |
+
#
|
| 79 |
+
# client: MUST_CLOSE
|
| 80 |
+
#
|
| 81 |
+
# This is fundamentally different from an event-based transition, because it
|
| 82 |
+
# doesn't matter how we arrived at the {client: DONE, keep-alive: False} state
|
| 83 |
+
# -- maybe the client transitioned SEND_BODY -> DONE, or keep-alive
|
| 84 |
+
# transitioned True -> False. Either way, once this precondition is satisfied,
|
| 85 |
+
# this transition is immediately triggered.
|
| 86 |
+
#
|
| 87 |
+
# What if two conflicting state-based transitions get enabled at the same
|
| 88 |
+
# time? In practice there's only one case where this arises (client DONE ->
|
| 89 |
+
# MIGHT_SWITCH_PROTOCOL versus DONE -> MUST_CLOSE), and we resolve it by
|
| 90 |
+
# explicitly prioritizing the DONE -> MIGHT_SWITCH_PROTOCOL transition.
|
| 91 |
+
#
|
| 92 |
+
# Implementation
|
| 93 |
+
# --------------
|
| 94 |
+
#
|
| 95 |
+
# The event-triggered transitions for the server and client machines are all
|
| 96 |
+
# stored explicitly in a table. Ditto for the state-triggered transitions that
|
| 97 |
+
# involve just the server and client state.
|
| 98 |
+
#
|
| 99 |
+
# The transitions for the other machines, and the state-triggered transitions
|
| 100 |
+
# that involve the other machines, are written out as explicit Python code.
|
| 101 |
+
#
|
| 102 |
+
# It'd be nice if there were some cleaner way to do all this. This isn't
|
| 103 |
+
# *too* terrible, but I feel like it could probably be better.
|
| 104 |
+
#
|
| 105 |
+
# WARNING
|
| 106 |
+
# -------
|
| 107 |
+
#
|
| 108 |
+
# The script that generates the state machine diagrams for the docs knows how
|
| 109 |
+
# to read out the EVENT_TRIGGERED_TRANSITIONS and STATE_TRIGGERED_TRANSITIONS
|
| 110 |
+
# tables. But it can't automatically read the transitions that are written
|
| 111 |
+
# directly in Python code. So if you touch those, you need to also update the
|
| 112 |
+
# script to keep it in sync!
|
| 113 |
+
from typing import cast, Dict, Optional, Set, Tuple, Type, Union
|
| 114 |
+
|
| 115 |
+
from ._events import *
|
| 116 |
+
from ._util import LocalProtocolError, Sentinel
|
| 117 |
+
|
| 118 |
+
# Everything in __all__ gets re-exported as part of the h11 public API.
|
| 119 |
+
__all__ = [
|
| 120 |
+
"CLIENT",
|
| 121 |
+
"SERVER",
|
| 122 |
+
"IDLE",
|
| 123 |
+
"SEND_RESPONSE",
|
| 124 |
+
"SEND_BODY",
|
| 125 |
+
"DONE",
|
| 126 |
+
"MUST_CLOSE",
|
| 127 |
+
"CLOSED",
|
| 128 |
+
"MIGHT_SWITCH_PROTOCOL",
|
| 129 |
+
"SWITCHED_PROTOCOL",
|
| 130 |
+
"ERROR",
|
| 131 |
+
]
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class CLIENT(Sentinel, metaclass=Sentinel):
|
| 135 |
+
pass
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class SERVER(Sentinel, metaclass=Sentinel):
|
| 139 |
+
pass
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# States
|
| 143 |
+
class IDLE(Sentinel, metaclass=Sentinel):
|
| 144 |
+
pass
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class SEND_RESPONSE(Sentinel, metaclass=Sentinel):
|
| 148 |
+
pass
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class SEND_BODY(Sentinel, metaclass=Sentinel):
|
| 152 |
+
pass
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class DONE(Sentinel, metaclass=Sentinel):
|
| 156 |
+
pass
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class MUST_CLOSE(Sentinel, metaclass=Sentinel):
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class CLOSED(Sentinel, metaclass=Sentinel):
|
| 164 |
+
pass
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class ERROR(Sentinel, metaclass=Sentinel):
|
| 168 |
+
pass
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
# Switch types
|
| 172 |
+
class MIGHT_SWITCH_PROTOCOL(Sentinel, metaclass=Sentinel):
|
| 173 |
+
pass
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class SWITCHED_PROTOCOL(Sentinel, metaclass=Sentinel):
|
| 177 |
+
pass
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class _SWITCH_UPGRADE(Sentinel, metaclass=Sentinel):
|
| 181 |
+
pass
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class _SWITCH_CONNECT(Sentinel, metaclass=Sentinel):
|
| 185 |
+
pass
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
EventTransitionType = Dict[
|
| 189 |
+
Type[Sentinel],
|
| 190 |
+
Dict[
|
| 191 |
+
Type[Sentinel],
|
| 192 |
+
Dict[Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], Type[Sentinel]],
|
| 193 |
+
],
|
| 194 |
+
]
|
| 195 |
+
|
| 196 |
+
EVENT_TRIGGERED_TRANSITIONS: EventTransitionType = {
|
| 197 |
+
CLIENT: {
|
| 198 |
+
IDLE: {Request: SEND_BODY, ConnectionClosed: CLOSED},
|
| 199 |
+
SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE},
|
| 200 |
+
DONE: {ConnectionClosed: CLOSED},
|
| 201 |
+
MUST_CLOSE: {ConnectionClosed: CLOSED},
|
| 202 |
+
CLOSED: {ConnectionClosed: CLOSED},
|
| 203 |
+
MIGHT_SWITCH_PROTOCOL: {},
|
| 204 |
+
SWITCHED_PROTOCOL: {},
|
| 205 |
+
ERROR: {},
|
| 206 |
+
},
|
| 207 |
+
SERVER: {
|
| 208 |
+
IDLE: {
|
| 209 |
+
ConnectionClosed: CLOSED,
|
| 210 |
+
Response: SEND_BODY,
|
| 211 |
+
# Special case: server sees client Request events, in this form
|
| 212 |
+
(Request, CLIENT): SEND_RESPONSE,
|
| 213 |
+
},
|
| 214 |
+
SEND_RESPONSE: {
|
| 215 |
+
InformationalResponse: SEND_RESPONSE,
|
| 216 |
+
Response: SEND_BODY,
|
| 217 |
+
(InformationalResponse, _SWITCH_UPGRADE): SWITCHED_PROTOCOL,
|
| 218 |
+
(Response, _SWITCH_CONNECT): SWITCHED_PROTOCOL,
|
| 219 |
+
},
|
| 220 |
+
SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE},
|
| 221 |
+
DONE: {ConnectionClosed: CLOSED},
|
| 222 |
+
MUST_CLOSE: {ConnectionClosed: CLOSED},
|
| 223 |
+
CLOSED: {ConnectionClosed: CLOSED},
|
| 224 |
+
SWITCHED_PROTOCOL: {},
|
| 225 |
+
ERROR: {},
|
| 226 |
+
},
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
StateTransitionType = Dict[
|
| 230 |
+
Tuple[Type[Sentinel], Type[Sentinel]], Dict[Type[Sentinel], Type[Sentinel]]
|
| 231 |
+
]
|
| 232 |
+
|
| 233 |
+
# NB: there are also some special-case state-triggered transitions hard-coded
|
| 234 |
+
# into _fire_state_triggered_transitions below.
|
| 235 |
+
STATE_TRIGGERED_TRANSITIONS: StateTransitionType = {
|
| 236 |
+
# (Client state, Server state) -> new states
|
| 237 |
+
# Protocol negotiation
|
| 238 |
+
(MIGHT_SWITCH_PROTOCOL, SWITCHED_PROTOCOL): {CLIENT: SWITCHED_PROTOCOL},
|
| 239 |
+
# Socket shutdown
|
| 240 |
+
(CLOSED, DONE): {SERVER: MUST_CLOSE},
|
| 241 |
+
(CLOSED, IDLE): {SERVER: MUST_CLOSE},
|
| 242 |
+
(ERROR, DONE): {SERVER: MUST_CLOSE},
|
| 243 |
+
(DONE, CLOSED): {CLIENT: MUST_CLOSE},
|
| 244 |
+
(IDLE, CLOSED): {CLIENT: MUST_CLOSE},
|
| 245 |
+
(DONE, ERROR): {CLIENT: MUST_CLOSE},
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
class ConnectionState:
|
| 250 |
+
def __init__(self) -> None:
|
| 251 |
+
# Extra bits of state that don't quite fit into the state model.
|
| 252 |
+
|
| 253 |
+
# If this is False then it enables the automatic DONE -> MUST_CLOSE
|
| 254 |
+
# transition. Don't set this directly; call .keep_alive_disabled()
|
| 255 |
+
self.keep_alive = True
|
| 256 |
+
|
| 257 |
+
# This is a subset of {UPGRADE, CONNECT}, containing the proposals
|
| 258 |
+
# made by the client for switching protocols.
|
| 259 |
+
self.pending_switch_proposals: Set[Type[Sentinel]] = set()
|
| 260 |
+
|
| 261 |
+
self.states: Dict[Type[Sentinel], Type[Sentinel]] = {CLIENT: IDLE, SERVER: IDLE}
|
| 262 |
+
|
| 263 |
+
def process_error(self, role: Type[Sentinel]) -> None:
|
| 264 |
+
self.states[role] = ERROR
|
| 265 |
+
self._fire_state_triggered_transitions()
|
| 266 |
+
|
| 267 |
+
def process_keep_alive_disabled(self) -> None:
|
| 268 |
+
self.keep_alive = False
|
| 269 |
+
self._fire_state_triggered_transitions()
|
| 270 |
+
|
| 271 |
+
def process_client_switch_proposal(self, switch_event: Type[Sentinel]) -> None:
|
| 272 |
+
self.pending_switch_proposals.add(switch_event)
|
| 273 |
+
self._fire_state_triggered_transitions()
|
| 274 |
+
|
| 275 |
+
def process_event(
|
| 276 |
+
self,
|
| 277 |
+
role: Type[Sentinel],
|
| 278 |
+
event_type: Type[Event],
|
| 279 |
+
server_switch_event: Optional[Type[Sentinel]] = None,
|
| 280 |
+
) -> None:
|
| 281 |
+
_event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type
|
| 282 |
+
if server_switch_event is not None:
|
| 283 |
+
assert role is SERVER
|
| 284 |
+
if server_switch_event not in self.pending_switch_proposals:
|
| 285 |
+
raise LocalProtocolError(
|
| 286 |
+
"Received server _SWITCH_UPGRADE event without a pending proposal"
|
| 287 |
+
)
|
| 288 |
+
_event_type = (event_type, server_switch_event)
|
| 289 |
+
if server_switch_event is None and _event_type is Response:
|
| 290 |
+
self.pending_switch_proposals = set()
|
| 291 |
+
self._fire_event_triggered_transitions(role, _event_type)
|
| 292 |
+
# Special case: the server state does get to see Request
|
| 293 |
+
# events.
|
| 294 |
+
if _event_type is Request:
|
| 295 |
+
assert role is CLIENT
|
| 296 |
+
self._fire_event_triggered_transitions(SERVER, (Request, CLIENT))
|
| 297 |
+
self._fire_state_triggered_transitions()
|
| 298 |
+
|
| 299 |
+
def _fire_event_triggered_transitions(
|
| 300 |
+
self,
|
| 301 |
+
role: Type[Sentinel],
|
| 302 |
+
event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]],
|
| 303 |
+
) -> None:
|
| 304 |
+
state = self.states[role]
|
| 305 |
+
try:
|
| 306 |
+
new_state = EVENT_TRIGGERED_TRANSITIONS[role][state][event_type]
|
| 307 |
+
except KeyError:
|
| 308 |
+
event_type = cast(Type[Event], event_type)
|
| 309 |
+
raise LocalProtocolError(
|
| 310 |
+
"can't handle event type {} when role={} and state={}".format(
|
| 311 |
+
event_type.__name__, role, self.states[role]
|
| 312 |
+
)
|
| 313 |
+
) from None
|
| 314 |
+
self.states[role] = new_state
|
| 315 |
+
|
| 316 |
+
def _fire_state_triggered_transitions(self) -> None:
|
| 317 |
+
# We apply these rules repeatedly until converging on a fixed point
|
| 318 |
+
while True:
|
| 319 |
+
start_states = dict(self.states)
|
| 320 |
+
|
| 321 |
+
# It could happen that both these special-case transitions are
|
| 322 |
+
# enabled at the same time:
|
| 323 |
+
#
|
| 324 |
+
# DONE -> MIGHT_SWITCH_PROTOCOL
|
| 325 |
+
# DONE -> MUST_CLOSE
|
| 326 |
+
#
|
| 327 |
+
# For example, this will always be true of a HTTP/1.0 client
|
| 328 |
+
# requesting CONNECT. If this happens, the protocol switch takes
|
| 329 |
+
# priority. From there the client will either go to
|
| 330 |
+
# SWITCHED_PROTOCOL, in which case it's none of our business when
|
| 331 |
+
# they close the connection, or else the server will deny the
|
| 332 |
+
# request, in which case the client will go back to DONE and then
|
| 333 |
+
# from there to MUST_CLOSE.
|
| 334 |
+
if self.pending_switch_proposals:
|
| 335 |
+
if self.states[CLIENT] is DONE:
|
| 336 |
+
self.states[CLIENT] = MIGHT_SWITCH_PROTOCOL
|
| 337 |
+
|
| 338 |
+
if not self.pending_switch_proposals:
|
| 339 |
+
if self.states[CLIENT] is MIGHT_SWITCH_PROTOCOL:
|
| 340 |
+
self.states[CLIENT] = DONE
|
| 341 |
+
|
| 342 |
+
if not self.keep_alive:
|
| 343 |
+
for role in (CLIENT, SERVER):
|
| 344 |
+
if self.states[role] is DONE:
|
| 345 |
+
self.states[role] = MUST_CLOSE
|
| 346 |
+
|
| 347 |
+
# Tabular state-triggered transitions
|
| 348 |
+
joint_state = (self.states[CLIENT], self.states[SERVER])
|
| 349 |
+
changes = STATE_TRIGGERED_TRANSITIONS.get(joint_state, {})
|
| 350 |
+
self.states.update(changes)
|
| 351 |
+
|
| 352 |
+
if self.states == start_states:
|
| 353 |
+
# Fixed point reached
|
| 354 |
+
return
|
| 355 |
+
|
| 356 |
+
def start_next_cycle(self) -> None:
|
| 357 |
+
if self.states != {CLIENT: DONE, SERVER: DONE}:
|
| 358 |
+
raise LocalProtocolError(
|
| 359 |
+
f"not in a reusable state. self.states={self.states}"
|
| 360 |
+
)
|
| 361 |
+
# Can't reach DONE/DONE with any of these active, but still, let's be
|
| 362 |
+
# sure.
|
| 363 |
+
assert self.keep_alive
|
| 364 |
+
assert not self.pending_switch_proposals
|
| 365 |
+
self.states = {CLIENT: IDLE, SERVER: IDLE}
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_util.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, NoReturn, Pattern, Tuple, Type, TypeVar, Union
|
| 2 |
+
|
| 3 |
+
__all__ = [
|
| 4 |
+
"ProtocolError",
|
| 5 |
+
"LocalProtocolError",
|
| 6 |
+
"RemoteProtocolError",
|
| 7 |
+
"validate",
|
| 8 |
+
"bytesify",
|
| 9 |
+
]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ProtocolError(Exception):
|
| 13 |
+
"""Exception indicating a violation of the HTTP/1.1 protocol.
|
| 14 |
+
|
| 15 |
+
This as an abstract base class, with two concrete base classes:
|
| 16 |
+
:exc:`LocalProtocolError`, which indicates that you tried to do something
|
| 17 |
+
that HTTP/1.1 says is illegal, and :exc:`RemoteProtocolError`, which
|
| 18 |
+
indicates that the remote peer tried to do something that HTTP/1.1 says is
|
| 19 |
+
illegal. See :ref:`error-handling` for details.
|
| 20 |
+
|
| 21 |
+
In addition to the normal :exc:`Exception` features, it has one attribute:
|
| 22 |
+
|
| 23 |
+
.. attribute:: error_status_hint
|
| 24 |
+
|
| 25 |
+
This gives a suggestion as to what status code a server might use if
|
| 26 |
+
this error occurred as part of a request.
|
| 27 |
+
|
| 28 |
+
For a :exc:`RemoteProtocolError`, this is useful as a suggestion for
|
| 29 |
+
how you might want to respond to a misbehaving peer, if you're
|
| 30 |
+
implementing a server.
|
| 31 |
+
|
| 32 |
+
For a :exc:`LocalProtocolError`, this can be taken as a suggestion for
|
| 33 |
+
how your peer might have responded to *you* if h11 had allowed you to
|
| 34 |
+
continue.
|
| 35 |
+
|
| 36 |
+
The default is 400 Bad Request, a generic catch-all for protocol
|
| 37 |
+
violations.
|
| 38 |
+
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self, msg: str, error_status_hint: int = 400) -> None:
|
| 42 |
+
if type(self) is ProtocolError:
|
| 43 |
+
raise TypeError("tried to directly instantiate ProtocolError")
|
| 44 |
+
Exception.__init__(self, msg)
|
| 45 |
+
self.error_status_hint = error_status_hint
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# Strategy: there are a number of public APIs where a LocalProtocolError can
|
| 49 |
+
# be raised (send(), all the different event constructors, ...), and only one
|
| 50 |
+
# public API where RemoteProtocolError can be raised
|
| 51 |
+
# (receive_data()). Therefore we always raise LocalProtocolError internally,
|
| 52 |
+
# and then receive_data will translate this into a RemoteProtocolError.
|
| 53 |
+
#
|
| 54 |
+
# Internally:
|
| 55 |
+
# LocalProtocolError is the generic "ProtocolError".
|
| 56 |
+
# Externally:
|
| 57 |
+
# LocalProtocolError is for local errors and RemoteProtocolError is for
|
| 58 |
+
# remote errors.
|
| 59 |
+
class LocalProtocolError(ProtocolError):
|
| 60 |
+
def _reraise_as_remote_protocol_error(self) -> NoReturn:
|
| 61 |
+
# After catching a LocalProtocolError, use this method to re-raise it
|
| 62 |
+
# as a RemoteProtocolError. This method must be called from inside an
|
| 63 |
+
# except: block.
|
| 64 |
+
#
|
| 65 |
+
# An easy way to get an equivalent RemoteProtocolError is just to
|
| 66 |
+
# modify 'self' in place.
|
| 67 |
+
self.__class__ = RemoteProtocolError # type: ignore
|
| 68 |
+
# But the re-raising is somewhat non-trivial -- you might think that
|
| 69 |
+
# now that we've modified the in-flight exception object, that just
|
| 70 |
+
# doing 'raise' to re-raise it would be enough. But it turns out that
|
| 71 |
+
# this doesn't work, because Python tracks the exception type
|
| 72 |
+
# (exc_info[0]) separately from the exception object (exc_info[1]),
|
| 73 |
+
# and we only modified the latter. So we really do need to re-raise
|
| 74 |
+
# the new type explicitly.
|
| 75 |
+
# On py3, the traceback is part of the exception object, so our
|
| 76 |
+
# in-place modification preserved it and we can just re-raise:
|
| 77 |
+
raise self
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class RemoteProtocolError(ProtocolError):
|
| 81 |
+
pass
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def validate(
|
| 85 |
+
regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any
|
| 86 |
+
) -> Dict[str, bytes]:
|
| 87 |
+
match = regex.fullmatch(data)
|
| 88 |
+
if not match:
|
| 89 |
+
if format_args:
|
| 90 |
+
msg = msg.format(*format_args)
|
| 91 |
+
raise LocalProtocolError(msg)
|
| 92 |
+
return match.groupdict()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# Sentinel values
|
| 96 |
+
#
|
| 97 |
+
# - Inherit identity-based comparison and hashing from object
|
| 98 |
+
# - Have a nice repr
|
| 99 |
+
# - Have a *bonus property*: type(sentinel) is sentinel
|
| 100 |
+
#
|
| 101 |
+
# The bonus property is useful if you want to take the return value from
|
| 102 |
+
# next_event() and do some sort of dispatch based on type(event).
|
| 103 |
+
|
| 104 |
+
_T_Sentinel = TypeVar("_T_Sentinel", bound="Sentinel")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class Sentinel(type):
|
| 108 |
+
def __new__(
|
| 109 |
+
cls: Type[_T_Sentinel],
|
| 110 |
+
name: str,
|
| 111 |
+
bases: Tuple[type, ...],
|
| 112 |
+
namespace: Dict[str, Any],
|
| 113 |
+
**kwds: Any
|
| 114 |
+
) -> _T_Sentinel:
|
| 115 |
+
assert bases == (Sentinel,)
|
| 116 |
+
v = super().__new__(cls, name, bases, namespace, **kwds)
|
| 117 |
+
v.__class__ = v # type: ignore
|
| 118 |
+
return v
|
| 119 |
+
|
| 120 |
+
def __repr__(self) -> str:
|
| 121 |
+
return self.__name__
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# Used for methods, request targets, HTTP versions, header names, and header
|
| 125 |
+
# values. Accepts ascii-strings, or bytes/bytearray/memoryview/..., and always
|
| 126 |
+
# returns bytes.
|
| 127 |
+
def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes:
|
| 128 |
+
# Fast-path:
|
| 129 |
+
if type(s) is bytes:
|
| 130 |
+
return s
|
| 131 |
+
if isinstance(s, str):
|
| 132 |
+
s = s.encode("ascii")
|
| 133 |
+
if isinstance(s, int):
|
| 134 |
+
raise TypeError("expected bytes-like object, not int")
|
| 135 |
+
return bytes(s)
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/_version.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file must be kept very simple, because it is consumed from several
|
| 2 |
+
# places -- it is imported by h11/__init__.py, execfile'd by setup.py, etc.
|
| 3 |
+
|
| 4 |
+
# We use a simple scheme:
|
| 5 |
+
# 1.0.0 -> 1.0.0+dev -> 1.1.0 -> 1.1.0+dev
|
| 6 |
+
# where the +dev versions are never released into the wild, they're just what
|
| 7 |
+
# we stick into the VCS in between releases.
|
| 8 |
+
#
|
| 9 |
+
# This is compatible with PEP 440:
|
| 10 |
+
# http://legacy.python.org/dev/peps/pep-0440/
|
| 11 |
+
# via the use of the "local suffix" "+dev", which is disallowed on index
|
| 12 |
+
# servers and causes 1.0.0+dev to sort after plain 1.0.0, which is what we
|
| 13 |
+
# want. (Contrast with the special suffix 1.0.0.dev, which sorts *before*
|
| 14 |
+
# 1.0.0.)
|
| 15 |
+
|
| 16 |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ytes function, which is
|
| 4 |
+
# calls.
|
| 5 |
+
#
|
| 6 |
+
# WRITERS is a dict describing how to pick a reader. It maps states to either:
|
| 7 |
+
# - a writer
|
| 8 |
+
# - or, for body writers, a dict of framin-dependent writer factories
|
| 9 |
+
|
| 10 |
+
from typing import Any, Callable, Dict, List, Tuple, Type, Union
|
| 11 |
+
|
| 12 |
+
from ._events import Data, EndOfMessage, Event, InformationalResponse, Request, Response
|
| 13 |
+
from ._headers import Headers
|
| 14 |
+
from ._state import CLIENT, IDLE, SEND_BODY, SEND_RESPONSE, SERVER
|
| 15 |
+
from ._util import LocalProtocolError, Sentinel
|
| 16 |
+
|
| 17 |
+
__all__ = ["WRITERS"]
|
| 18 |
+
|
| 19 |
+
Writer = Callable[[bytes], Any]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def write_headers(headers: Headers, write: Writer) -> None:
|
| 23 |
+
# "Since the Host field-value is critical information for handling a
|
| 24 |
+
# request, a user agent SHOULD generate Host as the first header field
|
| 25 |
+
# following the request-line." - RFC 7230
|
| 26 |
+
raw_items = headers._full_items
|
| 27 |
+
for raw_name, name, value in raw_items:
|
| 28 |
+
if name == b"host":
|
| 29 |
+
write(b"%s: %s\r\n" % (raw_name, value))
|
| 30 |
+
for raw_name, name, value in raw_items:
|
| 31 |
+
if name != b"host":
|
| 32 |
+
write(b"%s: %s\r\n" % (raw_name, value))
|
| 33 |
+
write(b"\r\n")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def write_request(request: Request, write: Writer) -> None:
|
| 37 |
+
if request.http_version != b"1.1":
|
| 38 |
+
raise LocalProtocolError("I only send HTTP/1.1")
|
| 39 |
+
write(b"%s %s HTTP/1.1\r\n" % (request.method, request.target))
|
| 40 |
+
write_headers(request.headers, write)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# Shared between InformationalResponse and Response
|
| 44 |
+
def write_any_response(
|
| 45 |
+
response: Union[InformationalResponse, Response], write: Writer
|
| 46 |
+
) -> None:
|
| 47 |
+
if response.http_version != b"1.1":
|
| 48 |
+
raise LocalProtocolError("I only send HTTP/1.1")
|
| 49 |
+
status_bytes = str(response.status_code).encode("ascii")
|
| 50 |
+
# We don't bother sending ascii status messages like "OK"; they're
|
| 51 |
+
# optional and ignored by the protocol. (But the space after the numeric
|
| 52 |
+
# status code is mandatory.)
|
| 53 |
+
#
|
| 54 |
+
# XX FIXME: could at least make an effort to pull out the status message
|
| 55 |
+
# from stdlib's http.HTTPStatus table. Or maybe just steal their enums
|
| 56 |
+
# (either by import or copy/paste). We already accept them as status codes
|
| 57 |
+
# since they're of type IntEnum < int.
|
| 58 |
+
write(b"HTTP/1.1 %s %s\r\n" % (status_bytes, response.reason))
|
| 59 |
+
write_headers(response.headers, write)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class BodyWriter:
|
| 63 |
+
def __call__(self, event: Event, write: Writer) -> None:
|
| 64 |
+
if type(event) is Data:
|
| 65 |
+
self.send_data(event.data, write)
|
| 66 |
+
elif type(event) is EndOfMessage:
|
| 67 |
+
self.send_eom(event.headers, write)
|
| 68 |
+
else: # pragma: no cover
|
| 69 |
+
assert False
|
| 70 |
+
|
| 71 |
+
def send_data(self, data: bytes, write: Writer) -> None:
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
def send_eom(self, headers: Headers, write: Writer) -> None:
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
#
|
| 79 |
+
# These are all careful not to do anything to 'data' except call len(data) and
|
| 80 |
+
# write(data). This allows us to transparently pass-through funny objects,
|
| 81 |
+
# like placeholder objects referring to files on disk that will be sent via
|
| 82 |
+
# sendfile(2).
|
| 83 |
+
#
|
| 84 |
+
class ContentLengthWriter(BodyWriter):
|
| 85 |
+
def __init__(self, length: int) -> None:
|
| 86 |
+
self._length = length
|
| 87 |
+
|
| 88 |
+
def send_data(self, data: bytes, write: Writer) -> None:
|
| 89 |
+
self._length -= len(data)
|
| 90 |
+
if self._length < 0:
|
| 91 |
+
raise LocalProtocolError("Too much data for declared Content-Length")
|
| 92 |
+
write(data)
|
| 93 |
+
|
| 94 |
+
def send_eom(self, headers: Headers, write: Writer) -> None:
|
| 95 |
+
if self._length != 0:
|
| 96 |
+
raise LocalProtocolError("Too little data for declared Content-Length")
|
| 97 |
+
if headers:
|
| 98 |
+
raise LocalProtocolError("Content-Length and trailers don't mix")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class ChunkedWriter(BodyWriter):
|
| 102 |
+
def send_data(self, data: bytes, write: Writer) -> None:
|
| 103 |
+
# if we encoded 0-length data in the naive way, it would look like an
|
| 104 |
+
# end-of-message.
|
| 105 |
+
if not data:
|
| 106 |
+
return
|
| 107 |
+
write(b"%x\r\n" % len(data))
|
| 108 |
+
write(data)
|
| 109 |
+
write(b"\r\n")
|
| 110 |
+
|
| 111 |
+
def send_eom(self, headers: Headers, write: Writer) -> None:
|
| 112 |
+
write(b"0\r\n")
|
| 113 |
+
write_headers(headers, write)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class Http10Writer(BodyWriter):
|
| 117 |
+
def send_data(self, data: bytes, write: Writer) -> None:
|
| 118 |
+
write(data)
|
| 119 |
+
|
| 120 |
+
def send_eom(self, headers: Headers, write: Writer) -> None:
|
| 121 |
+
if headers:
|
| 122 |
+
raise LocalProtocolError("can't send trailers to HTTP/1.0 client")
|
| 123 |
+
# no need to close the socket ourselves, that will be taken care of by
|
| 124 |
+
# Connection: close machinery
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
WritersType = Dict[
|
| 128 |
+
Union[Tuple[Type[Sentinel], Type[Sentinel]], Type[Sentinel]],
|
| 129 |
+
Union[
|
| 130 |
+
Dict[str, Type[BodyWriter]],
|
| 131 |
+
Callable[[Union[InformationalResponse, Response], Writer], None],
|
| 132 |
+
Callable[[Request, Writer], None],
|
| 133 |
+
],
|
| 134 |
+
]
|
| 135 |
+
|
| 136 |
+
WRITERS: WritersType = {
|
| 137 |
+
(CLIENT, IDLE): write_request,
|
| 138 |
+
(SERVER, IDLE): write_any_response,
|
| 139 |
+
(SERVER, SEND_RESPONSE): write_any_response,
|
| 140 |
+
SEND_BODY: {
|
| 141 |
+
"chunked": ChunkedWriter,
|
| 142 |
+
"content-length": ContentLengthWriter,
|
| 143 |
+
"http/1.0": Http10Writer,
|
| 144 |
+
},
|
| 145 |
+
}
|
.cache/uv/archive-v0/1RiQ6HVdoL0oOToZZlXTo/h11/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Marker
|
.cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx-0.28.1.dist-info/METADATA
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.3
|
| 2 |
+
Name: httpx
|
| 3 |
+
Version: 0.28.1
|
| 4 |
+
Summary: The next generation HTTP client.
|
| 5 |
+
Project-URL: Changelog, https://github.com/encode/httpx/blob/master/CHANGELOG.md
|
| 6 |
+
Project-URL: Documentation, https://www.python-httpx.org
|
| 7 |
+
Project-URL: Homepage, https://github.com/encode/httpx
|
| 8 |
+
Project-URL: Source, https://github.com/encode/httpx
|
| 9 |
+
Author-email: Tom Christie <tom@tomchristie.com>
|
| 10 |
+
License: BSD-3-Clause
|
| 11 |
+
Classifier: Development Status :: 4 - Beta
|
| 12 |
+
Classifier: Environment :: Web Environment
|
| 13 |
+
Classifier: Framework :: AsyncIO
|
| 14 |
+
Classifier: Framework :: Trio
|
| 15 |
+
Classifier: Intended Audience :: Developers
|
| 16 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 17 |
+
Classifier: Operating System :: OS Independent
|
| 18 |
+
Classifier: Programming Language :: Python :: 3
|
| 19 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 25 |
+
Classifier: Topic :: Internet :: WWW/HTTP
|
| 26 |
+
Requires-Python: >=3.8
|
| 27 |
+
Requires-Dist: anyio
|
| 28 |
+
Requires-Dist: certifi
|
| 29 |
+
Requires-Dist: httpcore==1.*
|
| 30 |
+
Requires-Dist: idna
|
| 31 |
+
Provides-Extra: brotli
|
| 32 |
+
Requires-Dist: brotli; (platform_python_implementation == 'CPython') and extra == 'brotli'
|
| 33 |
+
Requires-Dist: brotlicffi; (platform_python_implementation != 'CPython') and extra == 'brotli'
|
| 34 |
+
Provides-Extra: cli
|
| 35 |
+
Requires-Dist: click==8.*; extra == 'cli'
|
| 36 |
+
Requires-Dist: pygments==2.*; extra == 'cli'
|
| 37 |
+
Requires-Dist: rich<14,>=10; extra == 'cli'
|
| 38 |
+
Provides-Extra: http2
|
| 39 |
+
Requires-Dist: h2<5,>=3; extra == 'http2'
|
| 40 |
+
Provides-Extra: socks
|
| 41 |
+
Requires-Dist: socksio==1.*; extra == 'socks'
|
| 42 |
+
Provides-Extra: zstd
|
| 43 |
+
Requires-Dist: zstandard>=0.18.0; extra == 'zstd'
|
| 44 |
+
Description-Content-Type: text/markdown
|
| 45 |
+
|
| 46 |
+
<p align="center">
|
| 47 |
+
<a href="https://www.python-httpx.org/"><img width="350" height="208" src="https://raw.githubusercontent.com/encode/httpx/master/docs/img/butterfly.png" alt='HTTPX'></a>
|
| 48 |
+
</p>
|
| 49 |
+
|
| 50 |
+
<p align="center"><strong>HTTPX</strong> <em>- A next-generation HTTP client for Python.</em></p>
|
| 51 |
+
|
| 52 |
+
<p align="center">
|
| 53 |
+
<a href="https://github.com/encode/httpx/actions">
|
| 54 |
+
<img src="https://github.com/encode/httpx/workflows/Test%20Suite/badge.svg" alt="Test Suite">
|
| 55 |
+
</a>
|
| 56 |
+
<a href="https://pypi.org/project/httpx/">
|
| 57 |
+
<img src="https://badge.fury.io/py/httpx.svg" alt="Package version">
|
| 58 |
+
</a>
|
| 59 |
+
</p>
|
| 60 |
+
|
| 61 |
+
HTTPX is a fully featured HTTP client library for Python 3. It includes **an integrated command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync and async APIs**.
|
| 62 |
+
|
| 63 |
+
---
|
| 64 |
+
|
| 65 |
+
Install HTTPX using pip:
|
| 66 |
+
|
| 67 |
+
```shell
|
| 68 |
+
$ pip install httpx
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
Now, let's get started:
|
| 72 |
+
|
| 73 |
+
```pycon
|
| 74 |
+
>>> import httpx
|
| 75 |
+
>>> r = httpx.get('https://www.example.org/')
|
| 76 |
+
>>> r
|
| 77 |
+
<Response [200 OK]>
|
| 78 |
+
>>> r.status_code
|
| 79 |
+
200
|
| 80 |
+
>>> r.headers['content-type']
|
| 81 |
+
'text/html; charset=UTF-8'
|
| 82 |
+
>>> r.text
|
| 83 |
+
'<!doctype html>\n<html>\n<head>\n<title>Example Domain</title>...'
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
Or, using the command-line client.
|
| 87 |
+
|
| 88 |
+
```shell
|
| 89 |
+
$ pip install 'httpx[cli]' # The command line client is an optional dependency.
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
Which now allows us to use HTTPX directly from the command-line...
|
| 93 |
+
|
| 94 |
+
<p align="center">
|
| 95 |
+
<img width="700" src="https://raw.githubusercontent.com/encode/httpx/master/docs/img/httpx-help.png" alt='httpx --help'>
|
| 96 |
+
</p>
|
| 97 |
+
|
| 98 |
+
Sending a request...
|
| 99 |
+
|
| 100 |
+
<p align="center">
|
| 101 |
+
<img width="700" src="https://raw.githubusercontent.com/encode/httpx/master/docs/img/httpx-request.png" alt='httpx http://httpbin.org/json'>
|
| 102 |
+
</p>
|
| 103 |
+
|
| 104 |
+
## Features
|
| 105 |
+
|
| 106 |
+
HTTPX builds on the well-established usability of `requests`, and gives you:
|
| 107 |
+
|
| 108 |
+
* A broadly [requests-compatible API](https://www.python-httpx.org/compatibility/).
|
| 109 |
+
* An integrated command-line client.
|
| 110 |
+
* HTTP/1.1 [and HTTP/2 support](https://www.python-httpx.org/http2/).
|
| 111 |
+
* Standard synchronous interface, but with [async support if you need it](https://www.python-httpx.org/async/).
|
| 112 |
+
* Ability to make requests directly to [WSGI applications](https://www.python-httpx.org/advanced/transports/#wsgi-transport) or [ASGI applications](https://www.python-httpx.org/advanced/transports/#asgi-transport).
|
| 113 |
+
* Strict timeouts everywhere.
|
| 114 |
+
* Fully type annotated.
|
| 115 |
+
* 100% test coverage.
|
| 116 |
+
|
| 117 |
+
Plus all the standard features of `requests`...
|
| 118 |
+
|
| 119 |
+
* International Domains and URLs
|
| 120 |
+
* Keep-Alive & Connection Pooling
|
| 121 |
+
* Sessions with Cookie Persistence
|
| 122 |
+
* Browser-style SSL Verification
|
| 123 |
+
* Basic/Digest Authentication
|
| 124 |
+
* Elegant Key/Value Cookies
|
| 125 |
+
* Automatic Decompression
|
| 126 |
+
* Automatic Content Decoding
|
| 127 |
+
* Unicode Response Bodies
|
| 128 |
+
* Multipart File Uploads
|
| 129 |
+
* HTTP(S) Proxy Support
|
| 130 |
+
* Connection Timeouts
|
| 131 |
+
* Streaming Downloads
|
| 132 |
+
* .netrc Support
|
| 133 |
+
* Chunked Requests
|
| 134 |
+
|
| 135 |
+
## Installation
|
| 136 |
+
|
| 137 |
+
Install with pip:
|
| 138 |
+
|
| 139 |
+
```shell
|
| 140 |
+
$ pip install httpx
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
Or, to include the optional HTTP/2 support, use:
|
| 144 |
+
|
| 145 |
+
```shell
|
| 146 |
+
$ pip install httpx[http2]
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
HTTPX requires Python 3.8+.
|
| 150 |
+
|
| 151 |
+
## Documentation
|
| 152 |
+
|
| 153 |
+
Project documentation is available at [https://www.python-httpx.org/](https://www.python-httpx.org/).
|
| 154 |
+
|
| 155 |
+
For a run-through of all the basics, head over to the [QuickStart](https://www.python-httpx.org/quickstart/).
|
| 156 |
+
|
| 157 |
+
For more advanced topics, see the [Advanced Usage](https://www.python-httpx.org/advanced/) section, the [async support](https://www.python-httpx.org/async/) section, or the [HTTP/2](https://www.python-httpx.org/http2/) section.
|
| 158 |
+
|
| 159 |
+
The [Developer Interface](https://www.python-httpx.org/api/) provides a comprehensive API reference.
|
| 160 |
+
|
| 161 |
+
To find out about tools that integrate with HTTPX, see [Third Party Packages](https://www.python-httpx.org/third_party_packages/).
|
| 162 |
+
|
| 163 |
+
## Contribute
|
| 164 |
+
|
| 165 |
+
If you want to contribute with HTTPX check out the [Contributing Guide](https://www.python-httpx.org/contributing/) to learn how to start.
|
| 166 |
+
|
| 167 |
+
## Dependencies
|
| 168 |
+
|
| 169 |
+
The HTTPX project relies on these excellent libraries:
|
| 170 |
+
|
| 171 |
+
* `httpcore` - The underlying transport implementation for `httpx`.
|
| 172 |
+
* `h11` - HTTP/1.1 support.
|
| 173 |
+
* `certifi` - SSL certificates.
|
| 174 |
+
* `idna` - Internationalized domain name support.
|
| 175 |
+
* `sniffio` - Async library autodetection.
|
| 176 |
+
|
| 177 |
+
As well as these optional installs:
|
| 178 |
+
|
| 179 |
+
* `h2` - HTTP/2 support. *(Optional, with `httpx[http2]`)*
|
| 180 |
+
* `socksio` - SOCKS proxy support. *(Optional, with `httpx[socks]`)*
|
| 181 |
+
* `rich` - Rich terminal support. *(Optional, with `httpx[cli]`)*
|
| 182 |
+
* `click` - Command line client support. *(Optional, with `httpx[cli]`)*
|
| 183 |
+
* `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx[brotli]`)*
|
| 184 |
+
* `zstandard` - Decoding for "zstd" compressed responses. *(Optional, with `httpx[zstd]`)*
|
| 185 |
+
|
| 186 |
+
A huge amount of credit is due to `requests` for the API layout that
|
| 187 |
+
much of this work follows, as well as to `urllib3` for plenty of design
|
| 188 |
+
inspiration around the lower-level networking details.
|
| 189 |
+
|
| 190 |
+
---
|
| 191 |
+
|
| 192 |
+
<p align="center"><i>HTTPX is <a href="https://github.com/encode/httpx/blob/master/LICENSE.md">BSD licensed</a> code.<br/>Designed & crafted with care.</i><br/>— 🦋 —</p>
|
| 193 |
+
|
| 194 |
+
## Release Information
|
| 195 |
+
|
| 196 |
+
### Fixed
|
| 197 |
+
|
| 198 |
+
* Reintroduced supposedly-private `URLTypes` shortcut. (#2673)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
---
|
| 202 |
+
|
| 203 |
+
[Full changelog](https://github.com/encode/httpx/blob/master/CHANGELOG.md)
|
.cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx-0.28.1.dist-info/RECORD
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
httpx/__init__.py,sha256=CsaZe6yZj0rHg6322AWKWHGTMVr9txgEfD5P3_Rrz60,2171
|
| 2 |
+
httpx/__version__.py,sha256=LoUyYeOXTieGzuP_64UL0wxdtxjuu_QbOvE7NOg-IqU,108
|
| 3 |
+
httpx/_api.py,sha256=r_Zgs4jIpcPJLqK5dbbSayqo_iVMKFaxZCd-oOHxLEs,11743
|
| 4 |
+
httpx/_auth.py,sha256=Yr3QwaUSK17rGYx-7j-FdicFIzz4Y9FFV-1F4-7RXX4,11891
|
| 5 |
+
httpx/_client.py,sha256=xD-UG67-WMkeltAAOeGGj-cZ2RRTAm19sWRxlFY7_40,65714
|
| 6 |
+
httpx/_config.py,sha256=pPp2U-wicfcKsF-KYRE1LYdt3e6ERGeIoXZ8Gjo3LWc,8547
|
| 7 |
+
httpx/_content.py,sha256=LGGzrJTR3OvN4Mb1GVVNLXkXJH-6oKlwAttO9p5w_yg,8161
|
| 8 |
+
httpx/_decoders.py,sha256=p0dX8I0NEHexs3UGp4SsZutiMhsXrrWl6-GnqVb0iKM,12041
|
| 9 |
+
httpx/_exceptions.py,sha256=bxW7fxzgVMAdNTbwT0Vnq04gJDW1_gI_GFiQPuMyjL0,8527
|
| 10 |
+
httpx/_main.py,sha256=Cg9GMabiTT_swaDfUgIRitSwxLRMSwUDOm7LdSGqlA4,15626
|
| 11 |
+
httpx/_models.py,sha256=4__Guyv1gLxuZChwim8kfQNiIOcJ9acreFOSurvZfms,44700
|
| 12 |
+
httpx/_multipart.py,sha256=KOHEZZl6oohg9mPaKyyu345qq1rJLg35TUG3YAzXB3Y,9843
|
| 13 |
+
httpx/_status_codes.py,sha256=DYn-2ufBgMeXy5s8x3_TB7wjAuAAMewTakPrm5rXEsc,5639
|
| 14 |
+
httpx/_types.py,sha256=Jyh41GQq7AOev8IOWKDAg7zCbvHAfufmW5g_PiTtErY,2965
|
| 15 |
+
httpx/_urlparse.py,sha256=ZAmH47ONfkxrrj-PPYhGeiHjb6AjKCS-ANWIN4OL_KY,18546
|
| 16 |
+
httpx/_urls.py,sha256=dX99VR1DSOHpgo9Aq7PzYO4FKdxqKjwyNp8grf8dHN0,21550
|
| 17 |
+
httpx/_utils.py,sha256=_TVeqAKvxJkKHdz7dFeb4s0LZqQXgeFkXSgfiHBK_1o,8285
|
| 18 |
+
httpx/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 19 |
+
httpx/_transports/__init__.py,sha256=GbUoBSAOp7z-l-9j5YhMhR3DMIcn6FVLhj072O3Nnno,275
|
| 20 |
+
httpx/_transports/asgi.py,sha256=HRfiDYMPt4wQH2gFgHZg4c-i3sblo6bL5GTqcET-xz8,5501
|
| 21 |
+
httpx/_transports/base.py,sha256=kZS_VMbViYfF570pogUCJ1bulz-ybfL51Pqs9yktebU,2523
|
| 22 |
+
httpx/_transports/default.py,sha256=AzeaRUyVwCccTyyNJexDf0n1dFfzzydpdIQgvw7PLnk,13983
|
| 23 |
+
httpx/_transports/mock.py,sha256=PTo0d567RITXxGrki6kN7_67wwAxfwiMDcuXJiZCjEo,1232
|
| 24 |
+
httpx/_transports/wsgi.py,sha256=NcPX3Xap_EwCFZWO_OaSyQNuInCYx1QMNbO8GAei6jY,4825
|
| 25 |
+
httpx-0.28.1.dist-info/METADATA,sha256=_rubD48-gNV8gZnDBPNcQzboWB0dGNeYPJJ2a4J5OyU,7052
|
| 26 |
+
httpx-0.28.1.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
|
| 27 |
+
httpx-0.28.1.dist-info/entry_points.txt,sha256=2lVkdQmxLA1pNMgSN2eV89o90HCZezhmNwsy6ryKDSA,37
|
| 28 |
+
httpx-0.28.1.dist-info/licenses/LICENSE.md,sha256=TsWdVE8StfU5o6cW_TIaxYzNgDC0ZSIfLIgCAM3yjY0,1508
|
| 29 |
+
httpx-0.28.1.dist-info/RECORD,,
|
.cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx-0.28.1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.26.3
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
.cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx-0.28.1.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
httpx = httpx:main
|
.cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx-0.28.1.dist-info/licenses/LICENSE.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright © 2019, [Encode OSS Ltd](https://www.encode.io/).
|
| 2 |
+
All rights reserved.
|
| 3 |
+
|
| 4 |
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
| 5 |
+
|
| 6 |
+
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
| 7 |
+
|
| 8 |
+
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
| 9 |
+
|
| 10 |
+
* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
| 11 |
+
|
| 12 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
.cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx/__init__.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .__version__ import __description__, __title__, __version__
|
| 2 |
+
from ._api import *
|
| 3 |
+
from ._auth import *
|
| 4 |
+
from ._client import *
|
| 5 |
+
from ._config import *
|
| 6 |
+
from ._content import *
|
| 7 |
+
from ._exceptions import *
|
| 8 |
+
from ._models import *
|
| 9 |
+
from ._status_codes import *
|
| 10 |
+
from ._transports import *
|
| 11 |
+
from ._types import *
|
| 12 |
+
from ._urls import *
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
from ._main import main
|
| 16 |
+
except ImportError: # pragma: no cover
|
| 17 |
+
|
| 18 |
+
def main() -> None: # type: ignore
|
| 19 |
+
import sys
|
| 20 |
+
|
| 21 |
+
print(
|
| 22 |
+
"The httpx command line client could not run because the required "
|
| 23 |
+
"dependencies were not installed.\nMake sure you've installed "
|
| 24 |
+
"everything with: pip install 'httpx[cli]'"
|
| 25 |
+
)
|
| 26 |
+
sys.exit(1)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
__all__ = [
|
| 30 |
+
"__description__",
|
| 31 |
+
"__title__",
|
| 32 |
+
"__version__",
|
| 33 |
+
"ASGITransport",
|
| 34 |
+
"AsyncBaseTransport",
|
| 35 |
+
"AsyncByteStream",
|
| 36 |
+
"AsyncClient",
|
| 37 |
+
"AsyncHTTPTransport",
|
| 38 |
+
"Auth",
|
| 39 |
+
"BaseTransport",
|
| 40 |
+
"BasicAuth",
|
| 41 |
+
"ByteStream",
|
| 42 |
+
"Client",
|
| 43 |
+
"CloseError",
|
| 44 |
+
"codes",
|
| 45 |
+
"ConnectError",
|
| 46 |
+
"ConnectTimeout",
|
| 47 |
+
"CookieConflict",
|
| 48 |
+
"Cookies",
|
| 49 |
+
"create_ssl_context",
|
| 50 |
+
"DecodingError",
|
| 51 |
+
"delete",
|
| 52 |
+
"DigestAuth",
|
| 53 |
+
"get",
|
| 54 |
+
"head",
|
| 55 |
+
"Headers",
|
| 56 |
+
"HTTPError",
|
| 57 |
+
"HTTPStatusError",
|
| 58 |
+
"HTTPTransport",
|
| 59 |
+
"InvalidURL",
|
| 60 |
+
"Limits",
|
| 61 |
+
"LocalProtocolError",
|
| 62 |
+
"main",
|
| 63 |
+
"MockTransport",
|
| 64 |
+
"NetRCAuth",
|
| 65 |
+
"NetworkError",
|
| 66 |
+
"options",
|
| 67 |
+
"patch",
|
| 68 |
+
"PoolTimeout",
|
| 69 |
+
"post",
|
| 70 |
+
"ProtocolError",
|
| 71 |
+
"Proxy",
|
| 72 |
+
"ProxyError",
|
| 73 |
+
"put",
|
| 74 |
+
"QueryParams",
|
| 75 |
+
"ReadError",
|
| 76 |
+
"ReadTimeout",
|
| 77 |
+
"RemoteProtocolError",
|
| 78 |
+
"request",
|
| 79 |
+
"Request",
|
| 80 |
+
"RequestError",
|
| 81 |
+
"RequestNotRead",
|
| 82 |
+
"Response",
|
| 83 |
+
"ResponseNotRead",
|
| 84 |
+
"stream",
|
| 85 |
+
"StreamClosed",
|
| 86 |
+
"StreamConsumed",
|
| 87 |
+
"StreamError",
|
| 88 |
+
"SyncByteStream",
|
| 89 |
+
"Timeout",
|
| 90 |
+
"TimeoutException",
|
| 91 |
+
"TooManyRedirects",
|
| 92 |
+
"TransportError",
|
| 93 |
+
"UnsupportedProtocol",
|
| 94 |
+
"URL",
|
| 95 |
+
"USE_CLIENT_DEFAULT",
|
| 96 |
+
"WriteError",
|
| 97 |
+
"WriteTimeout",
|
| 98 |
+
"WSGITransport",
|
| 99 |
+
]
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
__locals = locals()
|
| 103 |
+
for __name in __all__:
|
| 104 |
+
if not __name.startswith("__"):
|
| 105 |
+
setattr(__locals[__name], "__module__", "httpx") # noqa
|
.cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx/__version__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__title__ = "httpx"
|
| 2 |
+
__description__ = "A next generation HTTP client, for Python 3."
|
| 3 |
+
__version__ = "0.28.1"
|
.cache/uv/archive-v0/DQCTxPNcHby_jM1D_eCAH/httpx/_api.py
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import typing
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
|
| 6 |
+
from ._client import Client
|
| 7 |
+
from ._config import DEFAULT_TIMEOUT_CONFIG
|
| 8 |
+
from ._models import Response
|
| 9 |
+
from ._types import (
|
| 10 |
+
AuthTypes,
|
| 11 |
+
CookieTypes,
|
| 12 |
+
HeaderTypes,
|
| 13 |
+
ProxyTypes,
|
| 14 |
+
QueryParamTypes,
|
| 15 |
+
RequestContent,
|
| 16 |
+
RequestData,
|
| 17 |
+
RequestFiles,
|
| 18 |
+
TimeoutTypes,
|
| 19 |
+
)
|
| 20 |
+
from ._urls import URL
|
| 21 |
+
|
| 22 |
+
if typing.TYPE_CHECKING:
|
| 23 |
+
import ssl # pragma: no cover
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
__all__ = [
|
| 27 |
+
"delete",
|
| 28 |
+
"get",
|
| 29 |
+
"head",
|
| 30 |
+
"options",
|
| 31 |
+
"patch",
|
| 32 |
+
"post",
|
| 33 |
+
"put",
|
| 34 |
+
"request",
|
| 35 |
+
"stream",
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def request(
|
| 40 |
+
method: str,
|
| 41 |
+
url: URL | str,
|
| 42 |
+
*,
|
| 43 |
+
params: QueryParamTypes | None = None,
|
| 44 |
+
content: RequestContent | None = None,
|
| 45 |
+
data: RequestData | None = None,
|
| 46 |
+
files: RequestFiles | None = None,
|
| 47 |
+
json: typing.Any | None = None,
|
| 48 |
+
headers: HeaderTypes | None = None,
|
| 49 |
+
cookies: CookieTypes | None = None,
|
| 50 |
+
auth: AuthTypes | None = None,
|
| 51 |
+
proxy: ProxyTypes | None = None,
|
| 52 |
+
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
|
| 53 |
+
follow_redirects: bool = False,
|
| 54 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 55 |
+
trust_env: bool = True,
|
| 56 |
+
) -> Response:
|
| 57 |
+
"""
|
| 58 |
+
Sends an HTTP request.
|
| 59 |
+
|
| 60 |
+
**Parameters:**
|
| 61 |
+
|
| 62 |
+
* **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`,
|
| 63 |
+
`HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`.
|
| 64 |
+
* **url** - URL for the new `Request` object.
|
| 65 |
+
* **params** - *(optional)* Query parameters to include in the URL, as a
|
| 66 |
+
string, dictionary, or sequence of two-tuples.
|
| 67 |
+
* **content** - *(optional)* Binary content to include in the body of the
|
| 68 |
+
request, as bytes or a byte iterator.
|
| 69 |
+
* **data** - *(optional)* Form data to include in the body of the request,
|
| 70 |
+
as a dictionary.
|
| 71 |
+
* **files** - *(optional)* A dictionary of upload files to include in the
|
| 72 |
+
body of the request.
|
| 73 |
+
* **json** - *(optional)* A JSON serializable object to include in the body
|
| 74 |
+
of the request.
|
| 75 |
+
* **headers** - *(optional)* Dictionary of HTTP headers to include in the
|
| 76 |
+
request.
|
| 77 |
+
* **cookies** - *(optional)* Dictionary of Cookie items to include in the
|
| 78 |
+
request.
|
| 79 |
+
* **auth** - *(optional)* An authentication class to use when sending the
|
| 80 |
+
request.
|
| 81 |
+
* **proxy** - *(optional)* A proxy URL where all the traffic should be routed.
|
| 82 |
+
* **timeout** - *(optional)* The timeout configuration to use when sending
|
| 83 |
+
the request.
|
| 84 |
+
* **follow_redirects** - *(optional)* Enables or disables HTTP redirects.
|
| 85 |
+
* **verify** - *(optional)* Either `True` to use an SSL context with the
|
| 86 |
+
default CA bundle, `False` to disable verification, or an instance of
|
| 87 |
+
`ssl.SSLContext` to use a custom context.
|
| 88 |
+
* **trust_env** - *(optional)* Enables or disables usage of environment
|
| 89 |
+
variables for configuration.
|
| 90 |
+
|
| 91 |
+
**Returns:** `Response`
|
| 92 |
+
|
| 93 |
+
Usage:
|
| 94 |
+
|
| 95 |
+
```
|
| 96 |
+
>>> import httpx
|
| 97 |
+
>>> response = httpx.request('GET', 'https://httpbin.org/get')
|
| 98 |
+
>>> response
|
| 99 |
+
<Response [200 OK]>
|
| 100 |
+
```
|
| 101 |
+
"""
|
| 102 |
+
with Client(
|
| 103 |
+
cookies=cookies,
|
| 104 |
+
proxy=proxy,
|
| 105 |
+
verify=verify,
|
| 106 |
+
timeout=timeout,
|
| 107 |
+
trust_env=trust_env,
|
| 108 |
+
) as client:
|
| 109 |
+
return client.request(
|
| 110 |
+
method=method,
|
| 111 |
+
url=url,
|
| 112 |
+
content=content,
|
| 113 |
+
data=data,
|
| 114 |
+
files=files,
|
| 115 |
+
json=json,
|
| 116 |
+
params=params,
|
| 117 |
+
headers=headers,
|
| 118 |
+
auth=auth,
|
| 119 |
+
follow_redirects=follow_redirects,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@contextmanager
|
| 124 |
+
def stream(
|
| 125 |
+
method: str,
|
| 126 |
+
url: URL | str,
|
| 127 |
+
*,
|
| 128 |
+
params: QueryParamTypes | None = None,
|
| 129 |
+
content: RequestContent | None = None,
|
| 130 |
+
data: RequestData | None = None,
|
| 131 |
+
files: RequestFiles | None = None,
|
| 132 |
+
json: typing.Any | None = None,
|
| 133 |
+
headers: HeaderTypes | None = None,
|
| 134 |
+
cookies: CookieTypes | None = None,
|
| 135 |
+
auth: AuthTypes | None = None,
|
| 136 |
+
proxy: ProxyTypes | None = None,
|
| 137 |
+
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
|
| 138 |
+
follow_redirects: bool = False,
|
| 139 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 140 |
+
trust_env: bool = True,
|
| 141 |
+
) -> typing.Iterator[Response]:
|
| 142 |
+
"""
|
| 143 |
+
Alternative to `httpx.request()` that streams the response body
|
| 144 |
+
instead of loading it into memory at once.
|
| 145 |
+
|
| 146 |
+
**Parameters**: See `httpx.request`.
|
| 147 |
+
|
| 148 |
+
See also: [Streaming Responses][0]
|
| 149 |
+
|
| 150 |
+
[0]: /quickstart#streaming-responses
|
| 151 |
+
"""
|
| 152 |
+
with Client(
|
| 153 |
+
cookies=cookies,
|
| 154 |
+
proxy=proxy,
|
| 155 |
+
verify=verify,
|
| 156 |
+
timeout=timeout,
|
| 157 |
+
trust_env=trust_env,
|
| 158 |
+
) as client:
|
| 159 |
+
with client.stream(
|
| 160 |
+
method=method,
|
| 161 |
+
url=url,
|
| 162 |
+
content=content,
|
| 163 |
+
data=data,
|
| 164 |
+
files=files,
|
| 165 |
+
json=json,
|
| 166 |
+
params=params,
|
| 167 |
+
headers=headers,
|
| 168 |
+
auth=auth,
|
| 169 |
+
follow_redirects=follow_redirects,
|
| 170 |
+
) as response:
|
| 171 |
+
yield response
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def get(
|
| 175 |
+
url: URL | str,
|
| 176 |
+
*,
|
| 177 |
+
params: QueryParamTypes | None = None,
|
| 178 |
+
headers: HeaderTypes | None = None,
|
| 179 |
+
cookies: CookieTypes | None = None,
|
| 180 |
+
auth: AuthTypes | None = None,
|
| 181 |
+
proxy: ProxyTypes | None = None,
|
| 182 |
+
follow_redirects: bool = False,
|
| 183 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 184 |
+
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
|
| 185 |
+
trust_env: bool = True,
|
| 186 |
+
) -> Response:
|
| 187 |
+
"""
|
| 188 |
+
Sends a `GET` request.
|
| 189 |
+
|
| 190 |
+
**Parameters**: See `httpx.request`.
|
| 191 |
+
|
| 192 |
+
Note that the `data`, `files`, `json` and `content` parameters are not available
|
| 193 |
+
on this function, as `GET` requests should not include a request body.
|
| 194 |
+
"""
|
| 195 |
+
return request(
|
| 196 |
+
"GET",
|
| 197 |
+
url,
|
| 198 |
+
params=params,
|
| 199 |
+
headers=headers,
|
| 200 |
+
cookies=cookies,
|
| 201 |
+
auth=auth,
|
| 202 |
+
proxy=proxy,
|
| 203 |
+
follow_redirects=follow_redirects,
|
| 204 |
+
verify=verify,
|
| 205 |
+
timeout=timeout,
|
| 206 |
+
trust_env=trust_env,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def options(
|
| 211 |
+
url: URL | str,
|
| 212 |
+
*,
|
| 213 |
+
params: QueryParamTypes | None = None,
|
| 214 |
+
headers: HeaderTypes | None = None,
|
| 215 |
+
cookies: CookieTypes | None = None,
|
| 216 |
+
auth: AuthTypes | None = None,
|
| 217 |
+
proxy: ProxyTypes | None = None,
|
| 218 |
+
follow_redirects: bool = False,
|
| 219 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 220 |
+
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
|
| 221 |
+
trust_env: bool = True,
|
| 222 |
+
) -> Response:
|
| 223 |
+
"""
|
| 224 |
+
Sends an `OPTIONS` request.
|
| 225 |
+
|
| 226 |
+
**Parameters**: See `httpx.request`.
|
| 227 |
+
|
| 228 |
+
Note that the `data`, `files`, `json` and `content` parameters are not available
|
| 229 |
+
on this function, as `OPTIONS` requests should not include a request body.
|
| 230 |
+
"""
|
| 231 |
+
return request(
|
| 232 |
+
"OPTIONS",
|
| 233 |
+
url,
|
| 234 |
+
params=params,
|
| 235 |
+
headers=headers,
|
| 236 |
+
cookies=cookies,
|
| 237 |
+
auth=auth,
|
| 238 |
+
proxy=proxy,
|
| 239 |
+
follow_redirects=follow_redirects,
|
| 240 |
+
verify=verify,
|
| 241 |
+
timeout=timeout,
|
| 242 |
+
trust_env=trust_env,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def head(
|
| 247 |
+
url: URL | str,
|
| 248 |
+
*,
|
| 249 |
+
params: QueryParamTypes | None = None,
|
| 250 |
+
headers: HeaderTypes | None = None,
|
| 251 |
+
cookies: CookieTypes | None = None,
|
| 252 |
+
auth: AuthTypes | None = None,
|
| 253 |
+
proxy: ProxyTypes | None = None,
|
| 254 |
+
follow_redirects: bool = False,
|
| 255 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 256 |
+
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
|
| 257 |
+
trust_env: bool = True,
|
| 258 |
+
) -> Response:
|
| 259 |
+
"""
|
| 260 |
+
Sends a `HEAD` request.
|
| 261 |
+
|
| 262 |
+
**Parameters**: See `httpx.request`.
|
| 263 |
+
|
| 264 |
+
Note that the `data`, `files`, `json` and `content` parameters are not available
|
| 265 |
+
on this function, as `HEAD` requests should not include a request body.
|
| 266 |
+
"""
|
| 267 |
+
return request(
|
| 268 |
+
"HEAD",
|
| 269 |
+
url,
|
| 270 |
+
params=params,
|
| 271 |
+
headers=headers,
|
| 272 |
+
cookies=cookies,
|
| 273 |
+
auth=auth,
|
| 274 |
+
proxy=proxy,
|
| 275 |
+
follow_redirects=follow_redirects,
|
| 276 |
+
verify=verify,
|
| 277 |
+
timeout=timeout,
|
| 278 |
+
trust_env=trust_env,
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def post(
|
| 283 |
+
url: URL | str,
|
| 284 |
+
*,
|
| 285 |
+
content: RequestContent | None = None,
|
| 286 |
+
data: RequestData | None = None,
|
| 287 |
+
files: RequestFiles | None = None,
|
| 288 |
+
json: typing.Any | None = None,
|
| 289 |
+
params: QueryParamTypes | None = None,
|
| 290 |
+
headers: HeaderTypes | None = None,
|
| 291 |
+
cookies: CookieTypes | None = None,
|
| 292 |
+
auth: AuthTypes | None = None,
|
| 293 |
+
proxy: ProxyTypes | None = None,
|
| 294 |
+
follow_redirects: bool = False,
|
| 295 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 296 |
+
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
|
| 297 |
+
trust_env: bool = True,
|
| 298 |
+
) -> Response:
|
| 299 |
+
"""
|
| 300 |
+
Sends a `POST` request.
|
| 301 |
+
|
| 302 |
+
**Parameters**: See `httpx.request`.
|
| 303 |
+
"""
|
| 304 |
+
return request(
|
| 305 |
+
"POST",
|
| 306 |
+
url,
|
| 307 |
+
content=content,
|
| 308 |
+
data=data,
|
| 309 |
+
files=files,
|
| 310 |
+
json=json,
|
| 311 |
+
params=params,
|
| 312 |
+
headers=headers,
|
| 313 |
+
cookies=cookies,
|
| 314 |
+
auth=auth,
|
| 315 |
+
proxy=proxy,
|
| 316 |
+
follow_redirects=follow_redirects,
|
| 317 |
+
verify=verify,
|
| 318 |
+
timeout=timeout,
|
| 319 |
+
trust_env=trust_env,
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def put(
|
| 324 |
+
url: URL | str,
|
| 325 |
+
*,
|
| 326 |
+
content: RequestContent | None = None,
|
| 327 |
+
data: RequestData | None = None,
|
| 328 |
+
files: RequestFiles | None = None,
|
| 329 |
+
json: typing.Any | None = None,
|
| 330 |
+
params: QueryParamTypes | None = None,
|
| 331 |
+
headers: HeaderTypes | None = None,
|
| 332 |
+
cookies: CookieTypes | None = None,
|
| 333 |
+
auth: AuthTypes | None = None,
|
| 334 |
+
proxy: ProxyTypes | None = None,
|
| 335 |
+
follow_redirects: bool = False,
|
| 336 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 337 |
+
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
|
| 338 |
+
trust_env: bool = True,
|
| 339 |
+
) -> Response:
|
| 340 |
+
"""
|
| 341 |
+
Sends a `PUT` request.
|
| 342 |
+
|
| 343 |
+
**Parameters**: See `httpx.request`.
|
| 344 |
+
"""
|
| 345 |
+
return request(
|
| 346 |
+
"PUT",
|
| 347 |
+
url,
|
| 348 |
+
content=content,
|
| 349 |
+
data=data,
|
| 350 |
+
files=files,
|
| 351 |
+
json=json,
|
| 352 |
+
params=params,
|
| 353 |
+
headers=headers,
|
| 354 |
+
cookies=cookies,
|
| 355 |
+
auth=auth,
|
| 356 |
+
proxy=proxy,
|
| 357 |
+
follow_redirects=follow_redirects,
|
| 358 |
+
verify=verify,
|
| 359 |
+
timeout=timeout,
|
| 360 |
+
trust_env=trust_env,
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def patch(
|
| 365 |
+
url: URL | str,
|
| 366 |
+
*,
|
| 367 |
+
content: RequestContent | None = None,
|
| 368 |
+
data: RequestData | None = None,
|
| 369 |
+
files: RequestFiles | None = None,
|
| 370 |
+
json: typing.Any | None = None,
|
| 371 |
+
params: QueryParamTypes | None = None,
|
| 372 |
+
headers: HeaderTypes | None = None,
|
| 373 |
+
cookies: CookieTypes | None = None,
|
| 374 |
+
auth: AuthTypes | None = None,
|
| 375 |
+
proxy: ProxyTypes | None = None,
|
| 376 |
+
follow_redirects: bool = False,
|
| 377 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 378 |
+
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
|
| 379 |
+
trust_env: bool = True,
|
| 380 |
+
) -> Response:
|
| 381 |
+
"""
|
| 382 |
+
Sends a `PATCH` request.
|
| 383 |
+
|
| 384 |
+
**Parameters**: See `httpx.request`.
|
| 385 |
+
"""
|
| 386 |
+
return request(
|
| 387 |
+
"PATCH",
|
| 388 |
+
url,
|
| 389 |
+
content=content,
|
| 390 |
+
data=data,
|
| 391 |
+
files=files,
|
| 392 |
+
json=json,
|
| 393 |
+
params=params,
|
| 394 |
+
headers=headers,
|
| 395 |
+
cookies=cookies,
|
| 396 |
+
auth=auth,
|
| 397 |
+
proxy=proxy,
|
| 398 |
+
follow_redirects=follow_redirects,
|
| 399 |
+
verify=verify,
|
| 400 |
+
timeout=timeout,
|
| 401 |
+
trust_env=trust_env,
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def delete(
|
| 406 |
+
url: URL | str,
|
| 407 |
+
*,
|
| 408 |
+
params: QueryParamTypes | None = None,
|
| 409 |
+
headers: HeaderTypes | None = None,
|
| 410 |
+
cookies: CookieTypes | None = None,
|
| 411 |
+
auth: AuthTypes | None = None,
|
| 412 |
+
proxy: ProxyTypes | None = None,
|
| 413 |
+
follow_redirects: bool = False,
|
| 414 |
+
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
|
| 415 |
+
verify: ssl.SSLContext | str | bool = True,
|
| 416 |
+
trust_env: bool = True,
|
| 417 |
+
) -> Response:
|
| 418 |
+
"""
|
| 419 |
+
Sends a `DELETE` request.
|
| 420 |
+
|
| 421 |
+
**Parameters**: See `httpx.request`.
|
| 422 |
+
|
| 423 |
+
Note that the `data`, `files`, `json` and `content` parameters are not available
|
| 424 |
+
on this function, as `DELETE` requests should not include a request body.
|
| 425 |
+
"""
|
| 426 |
+
return request(
|
| 427 |
+
"DELETE",
|
| 428 |
+
url,
|
| 429 |
+
params=params,
|
| 430 |
+
headers=headers,
|
| 431 |
+
cookies=cookies,
|
| 432 |
+
auth=auth,
|
| 433 |
+
proxy=proxy,
|
| 434 |
+
follow_redirects=follow_redirects,
|
| 435 |
+
verify=verify,
|
| 436 |
+
timeout=timeout,
|
| 437 |
+
trust_env=trust_env,
|
| 438 |
+
)
|