Initial commit: 首次建仓,建立目录结构

This commit is contained in:
FXY
2026-06-11 23:49:54 +08:00
commit 4038a476b5
9396 changed files with 2372905 additions and 0 deletions

View File

@ -0,0 +1,247 @@
<#
.Synopsis
Activate a Python virtual environment for the current PowerShell session.
.Description
Pushes the python executable for a virtual environment to the front of the
$Env:PATH environment variable and sets the prompt to signify that you are
in a Python virtual environment. Makes use of the command line switches as
well as the `pyvenv.cfg` file values present in the virtual environment.
.Parameter VenvDir
Path to the directory that contains the virtual environment to activate. The
default value for this is the parent of the directory that the Activate.ps1
script is located within.
.Parameter Prompt
The prompt prefix to display when this virtual environment is activated. By
default, this prompt is the name of the virtual environment folder (VenvDir)
surrounded by parentheses and followed by a single space (ie. '(.venv) ').
.Example
Activate.ps1
Activates the Python virtual environment that contains the Activate.ps1 script.
.Example
Activate.ps1 -Verbose
Activates the Python virtual environment that contains the Activate.ps1 script,
and shows extra information about the activation as it executes.
.Example
Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
Activates the Python virtual environment located in the specified location.
.Example
Activate.ps1 -Prompt "MyPython"
Activates the Python virtual environment that contains the Activate.ps1 script,
and prefixes the current prompt with the specified string (surrounded in
parentheses) while the virtual environment is active.
.Notes
On Windows, it may be required to enable this Activate.ps1 script by setting the
execution policy for the user. You can do this by issuing the following PowerShell
command:
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
For more information on Execution Policies:
https://go.microsoft.com/fwlink/?LinkID=135170
#>
Param(
[Parameter(Mandatory = $false)]
[String]
$VenvDir,
[Parameter(Mandatory = $false)]
[String]
$Prompt
)
<# Function declarations --------------------------------------------------- #>
<#
.Synopsis
Remove all shell session elements added by the Activate script, including the
addition of the virtual environment's Python executable from the beginning of
the PATH variable.
.Parameter NonDestructive
If present, do not remove this function from the global namespace for the
session.
#>
function global:deactivate ([switch]$NonDestructive) {
# Revert to original values
# The prior prompt:
if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
}
# The prior PYTHONHOME:
if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
}
# The prior PATH:
if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
Remove-Item -Path Env:_OLD_VIRTUAL_PATH
}
# Just remove the VIRTUAL_ENV altogether:
if (Test-Path -Path Env:VIRTUAL_ENV) {
Remove-Item -Path env:VIRTUAL_ENV
}
# Just remove VIRTUAL_ENV_PROMPT altogether.
if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
Remove-Item -Path env:VIRTUAL_ENV_PROMPT
}
# Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
}
# Leave deactivate function in the global namespace if requested:
if (-not $NonDestructive) {
Remove-Item -Path function:deactivate
}
}
<#
.Description
Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
given folder, and returns them in a map.
For each line in the pyvenv.cfg file, if that line can be parsed into exactly
two strings separated by `=` (with any amount of whitespace surrounding the =)
then it is considered a `key = value` line. The left hand string is the key,
the right hand is the value.
If the value starts with a `'` or a `"` then the first and last character is
stripped from the value before being captured.
.Parameter ConfigDir
Path to the directory that contains the `pyvenv.cfg` file.
#>
function Get-PyVenvConfig(
[String]
$ConfigDir
) {
Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
# Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
$pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
# An empty map will be returned if no config file is found.
$pyvenvConfig = @{ }
if ($pyvenvConfigPath) {
Write-Verbose "File exists, parse `key = value` lines"
$pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
$pyvenvConfigContent | ForEach-Object {
$keyval = $PSItem -split "\s*=\s*", 2
if ($keyval[0] -and $keyval[1]) {
$val = $keyval[1]
# Remove extraneous quotations around a string value.
if ("'""".Contains($val.Substring(0, 1))) {
$val = $val.Substring(1, $val.Length - 2)
}
$pyvenvConfig[$keyval[0]] = $val
Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
}
}
}
return $pyvenvConfig
}
<# Begin Activate script --------------------------------------------------- #>
# Determine the containing directory of this script
$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$VenvExecDir = Get-Item -Path $VenvExecPath
Write-Verbose "Activation script is located in path: '$VenvExecPath'"
Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
# Set values required in priority: CmdLine, ConfigFile, Default
# First, get the location of the virtual environment, it might not be
# VenvExecDir if specified on the command line.
if ($VenvDir) {
Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
}
else {
Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
$VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
Write-Verbose "VenvDir=$VenvDir"
}
# Next, read the `pyvenv.cfg` file to determine any required value such
# as `prompt`.
$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
# Next, set the prompt from the command line, or the config file, or
# just use the name of the virtual environment folder.
if ($Prompt) {
Write-Verbose "Prompt specified as argument, using '$Prompt'"
}
else {
Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
$Prompt = $pyvenvCfg['prompt'];
}
else {
Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
$Prompt = Split-Path -Path $venvDir -Leaf
}
}
Write-Verbose "Prompt = '$Prompt'"
Write-Verbose "VenvDir='$VenvDir'"
# Deactivate any currently active virtual environment, but leave the
# deactivate function in place.
deactivate -nondestructive
# Now set the environment variable VIRTUAL_ENV, used by many tools to determine
# that there is an activated venv.
$env:VIRTUAL_ENV = $VenvDir
if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
Write-Verbose "Setting prompt to '$Prompt'"
# Set the prompt to include the env name
# Make sure _OLD_VIRTUAL_PROMPT is global
function global:_OLD_VIRTUAL_PROMPT { "" }
Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
function global:prompt {
Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
_OLD_VIRTUAL_PROMPT
}
$env:VIRTUAL_ENV_PROMPT = $Prompt
}
# Clear PYTHONHOME
if (Test-Path -Path Env:PYTHONHOME) {
Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
Remove-Item -Path Env:PYTHONHOME
}
# Add the venv to the PATH
Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"

View File

@ -0,0 +1,70 @@
# This file must be used with "source bin/activate" *from bash*
# You cannot run it directly
deactivate () {
# reset old environment variables
if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
PATH="${_OLD_VIRTUAL_PATH:-}"
export PATH
unset _OLD_VIRTUAL_PATH
fi
if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
export PYTHONHOME
unset _OLD_VIRTUAL_PYTHONHOME
fi
# Call hash to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
hash -r 2> /dev/null
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
PS1="${_OLD_VIRTUAL_PS1:-}"
export PS1
unset _OLD_VIRTUAL_PS1
fi
unset VIRTUAL_ENV
unset VIRTUAL_ENV_PROMPT
if [ ! "${1:-}" = "nondestructive" ] ; then
# Self destruct!
unset -f deactivate
fi
}
# unset irrelevant variables
deactivate nondestructive
# on Windows, a path can contain colons and backslashes and has to be converted:
if [ "${OSTYPE:-}" = "cygwin" ] || [ "${OSTYPE:-}" = "msys" ] ; then
# transform D:\path\to\venv to /d/path/to/venv on MSYS
# and to /cygdrive/d/path/to/venv on Cygwin
export VIRTUAL_ENV=$(cygpath /home/ubuntu/trading_app/backend/venv)
else
# use the path as-is
export VIRTUAL_ENV=/home/ubuntu/trading_app/backend/venv
fi
_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/"bin":$PATH"
export PATH
# unset PYTHONHOME if set
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
# could use `if (set -u; : $PYTHONHOME) ;` in bash
if [ -n "${PYTHONHOME:-}" ] ; then
_OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
unset PYTHONHOME
fi
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
_OLD_VIRTUAL_PS1="${PS1:-}"
PS1='(venv) '"${PS1:-}"
export PS1
VIRTUAL_ENV_PROMPT='(venv) '
export VIRTUAL_ENV_PROMPT
fi
# Call hash to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
hash -r 2> /dev/null

View File

@ -0,0 +1,27 @@
# This file must be used with "source bin/activate.csh" *from csh*.
# You cannot run it directly.
# Created by Davide Di Blasi <davidedb@gmail.com>.
# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate'
# Unset irrelevant variables.
deactivate nondestructive
setenv VIRTUAL_ENV /home/ubuntu/trading_app/backend/venv
set _OLD_VIRTUAL_PATH="$PATH"
setenv PATH "$VIRTUAL_ENV/"bin":$PATH"
set _OLD_VIRTUAL_PROMPT="$prompt"
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
set prompt = '(venv) '"$prompt"
setenv VIRTUAL_ENV_PROMPT '(venv) '
endif
alias pydoc python -m pydoc
rehash

View File

@ -0,0 +1,69 @@
# This file must be used with "source <venv>/bin/activate.fish" *from fish*
# (https://fishshell.com/). You cannot run it directly.
function deactivate -d "Exit virtual environment and return to normal shell environment"
# reset old environment variables
if test -n "$_OLD_VIRTUAL_PATH"
set -gx PATH $_OLD_VIRTUAL_PATH
set -e _OLD_VIRTUAL_PATH
end
if test -n "$_OLD_VIRTUAL_PYTHONHOME"
set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
set -e _OLD_VIRTUAL_PYTHONHOME
end
if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
set -e _OLD_FISH_PROMPT_OVERRIDE
# prevents error when using nested fish instances (Issue #93858)
if functions -q _old_fish_prompt
functions -e fish_prompt
functions -c _old_fish_prompt fish_prompt
functions -e _old_fish_prompt
end
end
set -e VIRTUAL_ENV
set -e VIRTUAL_ENV_PROMPT
if test "$argv[1]" != "nondestructive"
# Self-destruct!
functions -e deactivate
end
end
# Unset irrelevant variables.
deactivate nondestructive
set -gx VIRTUAL_ENV /home/ubuntu/trading_app/backend/venv
set -gx _OLD_VIRTUAL_PATH $PATH
set -gx PATH "$VIRTUAL_ENV/"bin $PATH
# Unset PYTHONHOME if set.
if set -q PYTHONHOME
set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
set -e PYTHONHOME
end
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
# fish uses a function instead of an env var to generate the prompt.
# Save the current fish_prompt function as the function _old_fish_prompt.
functions -c fish_prompt _old_fish_prompt
# With the original prompt function renamed, we can override with our own.
function fish_prompt
# Save the return status of the last command.
set -l old_status $status
# Output the venv prompt; color taken from the blue of the Python logo.
printf "%s%s%s" (set_color 4B8BBE) '(venv) ' (set_color normal)
# Restore the return status of the previous command.
echo "exit $old_status" | .
# Output the original/"old" prompt.
_old_fish_prompt
end
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
set -gx VIRTUAL_ENV_PROMPT '(venv) '
end

8
dashboard/venv/bin/dotenv Executable file
View File

@ -0,0 +1,8 @@
#!/home/ubuntu/trading_app/backend/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from dotenv.__main__ import cli
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(cli())

8
dashboard/venv/bin/f2py Executable file
View File

@ -0,0 +1,8 @@
#!/home/ubuntu/trading_app/backend/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from numpy.f2py.f2py2e import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

8
dashboard/venv/bin/fastapi Executable file
View File

@ -0,0 +1,8 @@
#!/home/ubuntu/trading_app/backend/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from fastapi.cli import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

8
dashboard/venv/bin/idna Executable file
View File

@ -0,0 +1,8 @@
#!/home/ubuntu/trading_app/backend/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from idna.cli import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

8
dashboard/venv/bin/normalizer Executable file
View File

@ -0,0 +1,8 @@
#!/home/ubuntu/trading_app/backend/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from charset_normalizer.cli import cli_detect
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(cli_detect())

View File

@ -0,0 +1,8 @@
#!/home/ubuntu/trading_app/backend/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from numpy._configtool import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

8
dashboard/venv/bin/pip Executable file
View File

@ -0,0 +1,8 @@
#!/home/ubuntu/trading_app/backend/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

8
dashboard/venv/bin/pip3 Executable file
View File

@ -0,0 +1,8 @@
#!/home/ubuntu/trading_app/backend/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

8
dashboard/venv/bin/pip3.12 Executable file
View File

@ -0,0 +1,8 @@
#!/home/ubuntu/trading_app/backend/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

1
dashboard/venv/bin/python Symbolic link
View File

@ -0,0 +1 @@
python3

1
dashboard/venv/bin/python3 Symbolic link
View File

@ -0,0 +1 @@
/usr/bin/python3

View File

@ -0,0 +1 @@
python3

8
dashboard/venv/bin/uvicorn Executable file
View File

@ -0,0 +1,8 @@
#!/home/ubuntu/trading_app/backend/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from uvicorn.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

View File

@ -0,0 +1,239 @@
# don't import any costly modules
import os
import sys
report_url = (
"https://github.com/pypa/setuptools/issues/new?template=distutils-deprecation.yml"
)
def warn_distutils_present():
if 'distutils' not in sys.modules:
return
import warnings
warnings.warn(
"Distutils was imported before Setuptools, but importing Setuptools "
"also replaces the `distutils` module in `sys.modules`. This may lead "
"to undesirable behaviors or errors. To avoid these issues, avoid "
"using distutils directly, ensure that setuptools is installed in the "
"traditional way (e.g. not an editable install), and/or make sure "
"that setuptools is always imported before distutils."
)
def clear_distutils():
if 'distutils' not in sys.modules:
return
import warnings
warnings.warn(
"Setuptools is replacing distutils. Support for replacing "
"an already imported distutils is deprecated. In the future, "
"this condition will fail. "
f"Register concerns at {report_url}"
)
mods = [
name
for name in sys.modules
if name == "distutils" or name.startswith("distutils.")
]
for name in mods:
del sys.modules[name]
def enabled():
"""
Allow selection of distutils by environment variable.
"""
which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')
if which == 'stdlib':
import warnings
warnings.warn(
"Reliance on distutils from stdlib is deprecated. Users "
"must rely on setuptools to provide the distutils module. "
"Avoid importing distutils or import setuptools first, "
"and avoid setting SETUPTOOLS_USE_DISTUTILS=stdlib. "
f"Register concerns at {report_url}"
)
return which == 'local'
def ensure_local_distutils():
import importlib
clear_distutils()
# With the DistutilsMetaFinder in place,
# perform an import to cause distutils to be
# loaded from setuptools._distutils. Ref #2906.
with shim():
importlib.import_module('distutils')
# check that submodules load as expected
core = importlib.import_module('distutils.core')
assert '_distutils' in core.__file__, core.__file__
assert 'setuptools._distutils.log' not in sys.modules
def do_override():
"""
Ensure that the local copy of distutils is preferred over stdlib.
See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
for more motivation.
"""
if enabled():
warn_distutils_present()
ensure_local_distutils()
class _TrivialRe:
def __init__(self, *patterns) -> None:
self._patterns = patterns
def match(self, string):
return all(pat in string for pat in self._patterns)
class DistutilsMetaFinder:
def find_spec(self, fullname, path, target=None):
# optimization: only consider top level modules and those
# found in the CPython test suite.
if path is not None and not fullname.startswith('test.'):
return None
method_name = 'spec_for_{fullname}'.format(**locals())
method = getattr(self, method_name, lambda: None)
return method()
def spec_for_distutils(self):
if self.is_cpython():
return None
import importlib
import importlib.abc
import importlib.util
try:
mod = importlib.import_module('setuptools._distutils')
except Exception:
# There are a couple of cases where setuptools._distutils
# may not be present:
# - An older Setuptools without a local distutils is
# taking precedence. Ref #2957.
# - Path manipulation during sitecustomize removes
# setuptools from the path but only after the hook
# has been loaded. Ref #2980.
# In either case, fall back to stdlib behavior.
return None
class DistutilsLoader(importlib.abc.Loader):
def create_module(self, spec):
mod.__name__ = 'distutils'
return mod
def exec_module(self, module):
pass
return importlib.util.spec_from_loader(
'distutils', DistutilsLoader(), origin=mod.__file__
)
@staticmethod
def is_cpython():
"""
Suppress supplying distutils for CPython (build and tests).
Ref #2965 and #3007.
"""
return os.path.isfile('pybuilddir.txt')
def spec_for_pip(self):
"""
Ensure stdlib distutils when running under pip.
See pypa/pip#8761 for rationale.
"""
if sys.version_info >= (3, 12) or self.pip_imported_during_build():
return
clear_distutils()
self.spec_for_distutils = lambda: None
@classmethod
def pip_imported_during_build(cls):
"""
Detect if pip is being imported in a build script. Ref #2355.
"""
import traceback
return any(
cls.frame_file_is_setup(frame) for frame, line in traceback.walk_stack(None)
)
@staticmethod
def frame_file_is_setup(frame):
"""
Return True if the indicated frame suggests a setup.py file.
"""
# some frames may not have __file__ (#2940)
return frame.f_globals.get('__file__', '').endswith('setup.py')
def spec_for_sensitive_tests(self):
"""
Ensure stdlib distutils when running select tests under CPython.
python/cpython#91169
"""
clear_distutils()
self.spec_for_distutils = lambda: None
sensitive_tests = (
[
'test.test_distutils',
'test.test_peg_generator',
'test.test_importlib',
]
if sys.version_info < (3, 10)
else [
'test.test_distutils',
]
)
for name in DistutilsMetaFinder.sensitive_tests:
setattr(
DistutilsMetaFinder,
f'spec_for_{name}',
DistutilsMetaFinder.spec_for_sensitive_tests,
)
DISTUTILS_FINDER = DistutilsMetaFinder()
def add_shim():
DISTUTILS_FINDER in sys.meta_path or insert_shim()
class shim:
def __enter__(self) -> None:
insert_shim()
def __exit__(self, exc: object, value: object, tb: object) -> None:
_remove_shim()
def insert_shim():
sys.meta_path.insert(0, DISTUTILS_FINDER)
def _remove_shim():
try:
sys.meta_path.remove(DISTUTILS_FINDER)
except ValueError:
pass
if sys.version_info < (3, 12):
# DistutilsMetaFinder can only be disabled in Python < 3.12 (PEP 632)
remove_shim = _remove_shim

View File

@ -0,0 +1 @@
__import__('_distutils_hack').do_override()

View File

@ -0,0 +1,222 @@
Metadata-Version: 2.4
Name: aiodns
Version: 4.0.4
Summary: Simple DNS resolver for asyncio
Author-email: Saúl Ibarra Corretgé <s@saghul.net>
License-Expression: MIT
Project-URL: repository, https://github.com/aio-libs/aiodns.git
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: POSIX
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.10
Description-Content-Type: text/x-rst
License-File: LICENSE
Requires-Dist: pycares<6,>=5.0.0
Dynamic: license-file
===============================
Simple DNS resolver for asyncio
===============================
.. image:: https://badge.fury.io/py/aiodns.png
:target: https://pypi.org/project/aiodns/
.. image:: https://github.com/saghul/aiodns/workflows/CI/badge.svg
:target: https://github.com/saghul/aiodns/actions
aiodns provides a simple way for doing asynchronous DNS resolutions using `pycares <https://github.com/saghul/pycares>`_.
Example
=======
.. code:: python
import asyncio
import aiodns
async def main():
resolver = aiodns.DNSResolver()
result = await resolver.query_dns('google.com', 'A')
for record in result.answer:
print(record.data.addr)
asyncio.run(main())
The following query types are supported: A, AAAA, ANY, CAA, CNAME, MX, NAPTR, NS, PTR, SOA, SRV, TXT.
API
===
The API is pretty simple, the following functions are provided in the ``DNSResolver`` class:
* ``query_dns(host, type)``: Do a DNS resolution of the given type for the given hostname. It returns an
instance of ``asyncio.Future``. The result is a ``pycares.DNSResult`` object with ``answer``,
``authority``, and ``additional`` attributes containing lists of ``pycares.DNSRecord`` objects.
Each record has ``type``, ``ttl``, and ``data`` attributes. Check the `pycares documentation
<https://pycares.readthedocs.io/>`_ for details on the data attributes for each record type.
* ``query(host, type)``: **Deprecated** - use ``query_dns()`` instead. This method returns results
in a legacy format compatible with aiodns 3.x for backward compatibility.
* ``gethostbyname(host, socket_family)``: **Deprecated** - use ``getaddrinfo()`` instead.
Do a DNS resolution for the given hostname and the desired type of address family
(i.e. ``socket.AF_INET``). The actual result of the call is a ``asyncio.Future``.
* ``gethostbyaddr(name)``: Make a reverse lookup for an address.
* ``getaddrinfo(host, family, port, proto, type, flags)``: Resolve a host and port into a list of
address info entries.
* ``getnameinfo(sockaddr, flags)``: Resolve a socket address to a host and port.
* ``cancel()``: Cancel all pending DNS queries. All futures will get ``DNSError`` exception set, with
``ARES_ECANCELLED`` errno.
* ``close()``: Close the resolver. This releases all resources and cancels any pending queries. It must be called
when the resolver is no longer needed (e.g., application shutdown). The resolver should only be closed from the
event loop that created the resolver.
Migrating from aiodns 3.x
=========================
aiodns 4.x introduces a new ``query_dns()`` method that returns native pycares 5.x result types.
See the `pycares documentation <https://pycares.readthedocs.io/latest/channel.html#pycares.Channel.query>`_
for details on the result types. The old ``query()`` method is deprecated but continues to work
for backward compatibility.
.. code:: python
# Old API (deprecated)
result = await resolver.query('example.com', 'MX')
for record in result:
print(record.host, record.priority)
# New API (recommended)
result = await resolver.query_dns('example.com', 'MX')
for record in result.answer:
print(record.data.exchange, record.data.priority)
Future migration to aiodns 5.x
------------------------------
The temporary ``query_dns()`` naming allows gradual migration without breaking changes:
+-----------+---------------------------------------+--------------------------------------------+
| Version | ``query()`` | ``query_dns()`` |
+===========+=======================================+============================================+
| **4.x** | Deprecated, returns compat types | New API, returns pycares 5.x types |
+-----------+---------------------------------------+--------------------------------------------+
| **5.x** | New API, returns pycares 5.x types | Alias to ``query()`` for back compat |
+-----------+---------------------------------------+--------------------------------------------+
In aiodns 5.x, ``query()`` will become the primary API returning native pycares 5.x types,
and ``query_dns()`` will remain as an alias for backward compatibility. This allows downstream
projects to migrate at their own pace.
Async Context Manager Support
=============================
While not recommended for typical use cases, ``DNSResolver`` can be used as an async context manager
for scenarios where automatic cleanup is desired:
.. code:: python
async with aiodns.DNSResolver() as resolver:
result = await resolver.query_dns('example.com', 'A')
# resolver.close() is called automatically when exiting the context
**Important**: This pattern is discouraged for most applications because ``DNSResolver`` instances
are designed to be long-lived and reused for many queries. Creating and destroying resolvers
frequently adds unnecessary overhead. Use the context manager pattern only when you specifically
need automatic cleanup for short-lived resolver instances, such as in tests or one-off scripts.
Note for Windows users
======================
This library requires the use of an ``asyncio.SelectorEventLoop`` or ``winloop`` on Windows
**only** when using a custom build of ``pycares`` that links against a system-
provided ``c-ares`` library **without** thread-safety support. This is because
non-thread-safe builds of ``c-ares`` are incompatible with the default
``ProactorEventLoop`` on Windows.
If you're using the official prebuilt ``pycares`` wheels on PyPI (version 4.7.0 or
later), which include a thread-safe version of ``c-ares``, this limitation does
**not** apply and can be safely ignored.
The default event loop can be changed as follows (do this very early in your application):
.. code:: python
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
This may have other implications for the rest of your codebase, so make sure to test thoroughly.
Running the test suite
======================
To run the test suite: ``python -m pytest tests/``
Releasing (maintainers only)
============================
Releases are cut from ``master`` and published to PyPI automatically by the
``Release Wheels`` workflow when a GitHub Release is created.
1. **Prepare the release PR.** Bump ``__version__`` in ``aiodns/__init__.py``
and prepend a section to ``ChangeLog`` describing the user-facing changes
since the previous tag, in the same RST style as the existing entries
(``X.Y.Z`` header underlined with ``=``). Open the PR with the title
``Release X.Y.Z`` and merge it once CI is green.
Skip Dependabot bumps for dev tooling and CI actions; keep runtime
dependency bumps such as ``pycares``.
2. **Tag and publish the release.** From a clean checkout of ``master`` that
includes the merged release PR, generate the release notes from
``ChangeLog`` and create the GitHub release in one shot::
python scripts/release-notes.py --target X.Y.Z \
| gh release create vX.Y.Z --repo aio-libs/aiodns \
--title vX.Y.Z --notes-file -
The helper script reads ``__version__`` and the topmost ``ChangeLog``
section and aborts non-zero if they disagree, or if ``--target`` does
not match the current state on disk, so you can't accidentally publish
notes for a version the release PR hasn't actually landed yet.
3. **Watch the wheel build.** Publishing the GitHub release fires
``release-wheels.yml``, which builds wheels + sdist and pushes them to
`PyPI <https://pypi.org/project/aiodns/>`_ via trusted publishing
(no token required). Confirm the run succeeds::
gh run list --repo aio-libs/aiodns --workflow release-wheels.yml --limit 1
Author
======
Saúl Ibarra Corretgé <s@saghul.net>
License
=======
aiodns uses the MIT license, check LICENSE file.
Contributing
============
If you'd like to contribute, fork the project, make a patch and send a pull
request. Have a look at the surrounding code and please, make yours look
alike :-)

View File

@ -0,0 +1,13 @@
aiodns-4.0.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
aiodns-4.0.4.dist-info/METADATA,sha256=pVHVT-6YGLsPkHek3T52dJw-JihA1xholEOvymEPDLw,9022
aiodns-4.0.4.dist-info/RECORD,,
aiodns-4.0.4.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
aiodns-4.0.4.dist-info/licenses/LICENSE,sha256=PpHPp2ghq3DSKZgTbWdNIK6IhGOn6KfzdxZs_h7mT-s,1069
aiodns-4.0.4.dist-info/top_level.txt,sha256=5J2m3NWP4dezFZNpQoHaj8mv472iPcUzFboQoqWcEe4,7
aiodns/__init__.py,sha256=C8XPexYSfsN-sHf9hTmRMbGwgD189znOD-sduqQfkKQ,19381
aiodns/__pycache__/__init__.cpython-312.pyc,,
aiodns/__pycache__/compat.cpython-312.pyc,,
aiodns/__pycache__/error.cpython-312.pyc,,
aiodns/compat.py,sha256=lHsaYQ8ANvBpb6iqniMJoxuMXY_Cp-NmGRePvH4D91c,7941
aiodns/error.py,sha256=wYZFONch2rThb6sdMuKh_NUZBLJ5UgezHPwireqhQZE,1225
aiodns/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0

View File

@ -0,0 +1,5 @@
Wheel-Version: 1.0
Generator: setuptools (82.0.1)
Root-Is-Purelib: true
Tag: py3-none-any

View File

@ -0,0 +1,19 @@
Copyright (C) 2014 by Saúl Ibarra Corretgé
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,550 @@
from __future__ import annotations
import asyncio
import contextlib
import functools
import logging
import socket
import sys
import warnings
import weakref
from collections.abc import Callable, Iterable, Iterator, Sequence
from types import TracebackType
from typing import TYPE_CHECKING, Any, Literal, TypeVar, overload
import pycares
from . import error
from .compat import (
AresHostResult,
AresQueryAAAAResult,
AresQueryAResult,
AresQueryCAAResult,
AresQueryCNAMEResult,
AresQueryMXResult,
AresQueryNAPTRResult,
AresQueryNSResult,
AresQueryPTRResult,
AresQuerySOAResult,
AresQuerySRVResult,
AresQueryTXTResult,
QueryResult,
convert_result,
)
__version__ = '4.0.4'
__all__ = (
'DNSResolver',
'error',
)
_T = TypeVar('_T')
WINDOWS_SELECTOR_ERR_MSG = (
'aiodns needs a SelectorEventLoop on Windows. See more: '
'https://github.com/aio-libs/aiodns#note-for-windows-users'
)
_LOGGER = logging.getLogger(__name__)
query_type_map = {
'A': pycares.QUERY_TYPE_A,
'AAAA': pycares.QUERY_TYPE_AAAA,
'ANY': pycares.QUERY_TYPE_ANY,
'CAA': pycares.QUERY_TYPE_CAA,
'CNAME': pycares.QUERY_TYPE_CNAME,
'MX': pycares.QUERY_TYPE_MX,
'NAPTR': pycares.QUERY_TYPE_NAPTR,
'NS': pycares.QUERY_TYPE_NS,
'PTR': pycares.QUERY_TYPE_PTR,
'SOA': pycares.QUERY_TYPE_SOA,
'SRV': pycares.QUERY_TYPE_SRV,
'TXT': pycares.QUERY_TYPE_TXT,
}
query_class_map = {
'IN': pycares.QUERY_CLASS_IN,
'CHAOS': pycares.QUERY_CLASS_CHAOS,
'HS': pycares.QUERY_CLASS_HS,
'NONE': pycares.QUERY_CLASS_NONE,
'ANY': pycares.QUERY_CLASS_ANY,
}
class DNSResolver:
def __init__(
self,
nameservers: Sequence[str] | None = None,
loop: asyncio.AbstractEventLoop | None = None,
**kwargs: Any,
) -> None: # TODO(PY311): Use Unpack for kwargs.
self._closed = True
self.loop = loop or asyncio.get_event_loop()
if TYPE_CHECKING:
assert self.loop is not None
kwargs.pop('sock_state_cb', None)
timeout = kwargs.pop('timeout', None)
self._timeout = timeout
self._event_thread, self._channel = self._make_channel(**kwargs)
if nameservers:
self.nameservers = nameservers
self._read_fds: set[int] = set()
self._write_fds: set[int] = set()
self._timer: asyncio.TimerHandle | None = None
self._closed = False
def _make_channel(self, **kwargs: Any) -> tuple[bool, pycares.Channel]:
# pycares 5+ uses event_thread by default when sock_state_cb
# is not provided
try:
return True, pycares.Channel(timeout=self._timeout, **kwargs)
except pycares.AresError as e:
if sys.platform == 'linux':
_LOGGER.warning(
'Failed to create DNS resolver channel with automatic '
'monitoring of resolver configuration changes. This '
'usually means the system ran out of inotify watches. '
'Falling back to socket state callback. Consider '
'increasing the system inotify watch limit: %s',
e,
)
else:
_LOGGER.warning(
'Failed to create DNS resolver channel with automatic '
'monitoring of resolver configuration changes. '
'Falling back to socket state callback: %s',
e,
)
# Fall back to sock_state_cb (needs SelectorEventLoop on Windows)
if sys.platform == 'win32' and not isinstance(
self.loop, asyncio.SelectorEventLoop
):
try:
import winloop
if not isinstance(self.loop, winloop.Loop):
raise RuntimeError(WINDOWS_SELECTOR_ERR_MSG)
except ModuleNotFoundError as ex:
raise RuntimeError(WINDOWS_SELECTOR_ERR_MSG) from ex
# Use weak reference for deterministic cleanup. Without it there's a
# reference cycle (DNSResolver -> _channel -> callback -> DNSResolver).
# Python 3.4+ can handle cycles with __del__, but weak ref ensures
# cleanup happens immediately when last reference is dropped.
weak_self = weakref.ref(self)
def sock_state_cb_wrapper(
fd: int, readable: bool, writable: bool
) -> None:
this = weak_self()
if this is not None:
this._sock_state_cb(fd, readable, writable)
return False, pycares.Channel(
sock_state_cb=sock_state_cb_wrapper,
timeout=self._timeout,
**kwargs,
)
@property
def nameservers(self) -> Sequence[str]:
# pycares 5.x returns servers with port (e.g., '8.8.8.8:53')
# Strip port for backward compatibility with pycares 4.x
return [s.rsplit(':', 1)[0] for s in self._channel.servers]
@nameservers.setter
def nameservers(self, value: Iterable[str | bytes]) -> None:
self._channel.servers = value
def _callback(
self, fut: asyncio.Future[_T], result: _T, errorno: int | None
) -> None:
# The future can already be done if pycares raised synchronously
# and _capture_ares_error set the exception before c-ares delivered
# the same error through this callback.
if fut.done():
return
if errorno is not None:
fut.set_exception(
error.DNSError(errorno, pycares.errno.strerror(errorno))
)
else:
fut.set_result(result)
def _get_future_callback(
self,
) -> tuple[asyncio.Future[_T], Callable[[_T, int | None], None]]:
"""Return a future and a callback to set the result of the future."""
cb: Callable[[_T, int | None], None]
future: asyncio.Future[_T] = self.loop.create_future()
if self._event_thread:
cb = functools.partial( # type: ignore[assignment]
self.loop.call_soon_threadsafe,
self._callback, # type: ignore[arg-type]
future,
)
else:
cb = functools.partial(self._callback, future)
return future, cb
def _query_callback(
self,
fut: asyncio.Future[QueryResult],
qtype: int,
result: pycares.DNSResult,
errorno: int | None,
) -> None:
"""Callback for query that converts results to compatible format."""
# See _callback for why we guard on done() rather than cancelled().
if fut.done():
return
if errorno is not None:
fut.set_exception(
error.DNSError(errorno, pycares.errno.strerror(errorno))
)
return
try:
converted = convert_result(result, qtype)
except error.DNSError as exc:
fut.set_exception(exc)
else:
fut.set_result(converted)
def _get_query_future_callback(
self, qtype: int
) -> tuple[asyncio.Future[QueryResult], Callable[..., None]]:
"""Return a future and callback for query with result conversion."""
future: asyncio.Future[QueryResult] = self.loop.create_future()
cb: Callable[..., None]
if self._event_thread:
cb = functools.partial( # type: ignore[assignment]
self.loop.call_soon_threadsafe,
self._query_callback, # type: ignore[arg-type]
future,
qtype,
)
else:
cb = functools.partial(self._query_callback, future, qtype)
return future, cb
@contextlib.contextmanager
def _capture_ares_error(self, fut: asyncio.Future[_T]) -> Iterator[None]:
# When pycares raises synchronously (e.g. ARES_EBADNAME for a
# malformed hostname), c-ares may also invoke the callback first,
# leaving the future already done. Route the error through the
# future so callers can rely on `await` to raise.
try:
yield
except pycares.AresError as exc:
if fut.done():
return
# pycares always raises (errno, message), but be defensive:
# an args-less AresError should still resolve the future to
# avoid an indefinite hang on `await`.
errno = exc.args[0] if exc.args else error.ARES_EFORMERR
fut.set_exception(
error.DNSError(errno, pycares.errno.strerror(errno))
)
@overload
def query(
self, host: str, qtype: Literal['A'], qclass: str | None = ...
) -> asyncio.Future[list[AresQueryAResult]]: ...
@overload
def query(
self, host: str, qtype: Literal['AAAA'], qclass: str | None = ...
) -> asyncio.Future[list[AresQueryAAAAResult]]: ...
@overload
def query(
self, host: str, qtype: Literal['CAA'], qclass: str | None = ...
) -> asyncio.Future[list[AresQueryCAAResult]]: ...
@overload
def query(
self, host: str, qtype: Literal['CNAME'], qclass: str | None = ...
) -> asyncio.Future[AresQueryCNAMEResult]: ...
@overload
def query(
self, host: str, qtype: Literal['MX'], qclass: str | None = ...
) -> asyncio.Future[list[AresQueryMXResult]]: ...
@overload
def query(
self, host: str, qtype: Literal['NAPTR'], qclass: str | None = ...
) -> asyncio.Future[list[AresQueryNAPTRResult]]: ...
@overload
def query(
self, host: str, qtype: Literal['NS'], qclass: str | None = ...
) -> asyncio.Future[list[AresQueryNSResult]]: ...
@overload
def query(
self, host: str, qtype: Literal['PTR'], qclass: str | None = ...
) -> asyncio.Future[AresQueryPTRResult]: ...
@overload
def query(
self, host: str, qtype: Literal['SOA'], qclass: str | None = ...
) -> asyncio.Future[AresQuerySOAResult]: ...
@overload
def query(
self, host: str, qtype: Literal['SRV'], qclass: str | None = ...
) -> asyncio.Future[list[AresQuerySRVResult]]: ...
@overload
def query(
self, host: str, qtype: Literal['TXT'], qclass: str | None = ...
) -> asyncio.Future[list[AresQueryTXTResult]]: ...
def query(
self, host: str, qtype: str, qclass: str | None = None
) -> asyncio.Future[list[Any]] | asyncio.Future[Any]:
"""Query DNS records (deprecated, use query_dns instead)."""
warnings.warn(
'query() is deprecated, use query_dns() instead',
DeprecationWarning,
stacklevel=2,
)
try:
qtype_int = query_type_map[qtype]
except KeyError as e:
raise ValueError(f'invalid query type: {qtype}') from e
qclass_int: int | None = None
if qclass is not None:
try:
qclass_int = query_class_map[qclass]
except KeyError as e:
raise ValueError(f'invalid query class: {qclass}') from e
fut, cb = self._get_query_future_callback(qtype_int)
with self._capture_ares_error(fut):
if qclass_int is not None:
self._channel.query(
host, qtype_int, query_class=qclass_int, callback=cb
)
else:
self._channel.query(host, qtype_int, callback=cb)
return fut
def query_dns(
self, host: str, qtype: str, qclass: str | None = None
) -> asyncio.Future[pycares.DNSResult]:
"""Query DNS records, returning native pycares 5.x DNSResult."""
try:
qtype_int = query_type_map[qtype]
except KeyError as e:
raise ValueError(f'invalid query type: {qtype}') from e
qclass_int: int | None = None
if qclass is not None:
try:
qclass_int = query_class_map[qclass]
except KeyError as e:
raise ValueError(f'invalid query class: {qclass}') from e
fut: asyncio.Future[pycares.DNSResult]
fut, cb = self._get_future_callback()
with self._capture_ares_error(fut):
if qclass_int is not None:
self._channel.query(
host, qtype_int, query_class=qclass_int, callback=cb
)
else:
self._channel.query(host, qtype_int, callback=cb)
return fut
def _gethostbyname_callback(
self,
fut: asyncio.Future[AresHostResult],
host: str,
result: pycares.AddrInfoResult | None,
errorno: int | None,
) -> None:
"""Callback for gethostbyname that converts AddrInfoResult."""
# See _callback for why we guard on done() rather than cancelled().
if fut.done():
return
if errorno is not None:
fut.set_exception(
error.DNSError(errorno, pycares.errno.strerror(errorno))
)
else:
assert result is not None # noqa: S101
# node.addr is (address_bytes, port) - extract and decode
addresses = [node.addr[0].decode() for node in result.nodes]
# Get canonical name from cnames if available
name = result.cnames[0].name if result.cnames else host
fut.set_result(
AresHostResult(name=name, aliases=[], addresses=addresses)
)
def gethostbyname(
self, host: str, family: socket.AddressFamily
) -> asyncio.Future[AresHostResult]:
"""
Resolve hostname to addresses.
Deprecated: Use getaddrinfo() instead. This is implemented using
getaddrinfo as pycares 5.x removed the gethostbyname method.
"""
warnings.warn(
'gethostbyname() is deprecated, use getaddrinfo() instead',
DeprecationWarning,
stacklevel=2,
)
fut: asyncio.Future[AresHostResult] = self.loop.create_future()
cb: Callable[..., None]
if self._event_thread:
cb = functools.partial( # type: ignore[assignment]
self.loop.call_soon_threadsafe,
self._gethostbyname_callback, # type: ignore[arg-type]
fut,
host,
)
else:
cb = functools.partial(self._gethostbyname_callback, fut, host)
with self._capture_ares_error(fut):
self._channel.getaddrinfo(host, None, family=family, callback=cb)
return fut
def getaddrinfo(
self,
host: str,
family: socket.AddressFamily = socket.AF_UNSPEC,
port: int | None = None,
proto: int = 0,
type: int = 0,
flags: int = 0,
) -> asyncio.Future[pycares.AddrInfoResult]:
fut: asyncio.Future[pycares.AddrInfoResult]
fut, cb = self._get_future_callback()
with self._capture_ares_error(fut):
self._channel.getaddrinfo(
host,
port,
family=family,
type=type,
proto=proto,
flags=flags,
callback=cb,
)
return fut
def getnameinfo(
self,
sockaddr: tuple[str, int] | tuple[str, int, int, int],
flags: int = 0,
) -> asyncio.Future[pycares.NameInfoResult]:
fut: asyncio.Future[pycares.NameInfoResult]
fut, cb = self._get_future_callback()
with self._capture_ares_error(fut):
self._channel.getnameinfo(sockaddr, flags, callback=cb)
return fut
def gethostbyaddr(self, name: str) -> asyncio.Future[pycares.HostResult]:
fut: asyncio.Future[pycares.HostResult]
fut, cb = self._get_future_callback()
with self._capture_ares_error(fut):
self._channel.gethostbyaddr(name, callback=cb)
return fut
def cancel(self) -> None:
self._channel.cancel()
def _sock_state_cb(self, fd: int, readable: bool, writable: bool) -> None:
if readable or writable:
if readable:
self.loop.add_reader(
fd, self._channel.process_fd, fd, pycares.ARES_SOCKET_BAD
)
self._read_fds.add(fd)
if writable:
self.loop.add_writer(
fd, self._channel.process_fd, pycares.ARES_SOCKET_BAD, fd
)
self._write_fds.add(fd)
if self._timer is None:
self._start_timer()
else:
# socket is now closed
if fd in self._read_fds:
self._read_fds.discard(fd)
self.loop.remove_reader(fd)
if fd in self._write_fds:
self._write_fds.discard(fd)
self.loop.remove_writer(fd)
if (
not self._read_fds
and not self._write_fds
and self._timer is not None
):
self._timer.cancel()
self._timer = None
def _timer_cb(self) -> None:
if self._read_fds or self._write_fds:
self._channel.process_fd(
pycares.ARES_SOCKET_BAD, pycares.ARES_SOCKET_BAD
)
self._start_timer()
else:
self._timer = None
def _start_timer(self) -> None:
timeout = self._timeout
if timeout is None or timeout < 0 or timeout > 1:
timeout = 1
elif timeout == 0:
timeout = 0.1
self._timer = self.loop.call_later(timeout, self._timer_cb)
def _cleanup(self) -> None:
"""Cleanup timers and file descriptors when closing resolver."""
if self._closed:
return
# Mark as closed first to prevent double cleanup
self._closed = True
# Cancel timer if running
if self._timer is not None:
self._timer.cancel()
self._timer = None
# Remove all file descriptors
for fd in self._read_fds:
self.loop.remove_reader(fd)
for fd in self._write_fds:
self.loop.remove_writer(fd)
self._read_fds.clear()
self._write_fds.clear()
self._channel.close()
async def close(self) -> None:
"""
Cleanly close the DNS resolver.
This should be called to ensure all resources are properly released.
After calling close(), the resolver should not be used again.
"""
if not self._closed:
self._channel.cancel()
self._cleanup()
async def __aenter__(self) -> DNSResolver:
"""Enter the async context manager."""
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
"""Exit the async context manager."""
await self.close()
def __del__(self) -> None:
"""Handle cleanup when the resolver is garbage collected."""
# Check if we have a channel to clean up
# This can happen if an exception occurs during __init__ before
# _channel is created (e.g., RuntimeError on Windows
# without proper loop)
if hasattr(self, '_channel'):
self._cleanup()

View File

@ -0,0 +1,288 @@
"""
Compatibility layer for pycares 5.x API.
This module provides result types compatible with pycares 4.x API
to maintain backward compatibility with existing code.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Union, cast
import pycares
from . import error
_SINGLE_RESULT_QTYPES = frozenset(
{
pycares.QUERY_TYPE_CNAME,
pycares.QUERY_TYPE_SOA,
pycares.QUERY_TYPE_PTR,
}
)
def _maybe_str(data: bytes) -> str | bytes:
"""Decode bytes as ASCII, return bytes if decode fails (pycares 4.x)."""
try:
return data.decode('ascii')
except UnicodeDecodeError:
return data
@dataclass(frozen=True, slots=True)
class AresQueryAResult:
"""A record result (compatible with pycares 4.x ares_query_a_result)."""
host: str
ttl: int
@dataclass(frozen=True, slots=True)
class AresQueryAAAAResult:
"""AAAA record result (pycares 4.x compat)."""
host: str
ttl: int
@dataclass(frozen=True, slots=True)
class AresQueryCNAMEResult:
"""CNAME record result (pycares 4.x compat)."""
cname: str
ttl: int
@dataclass(frozen=True, slots=True)
class AresQueryMXResult:
"""MX record result (pycares 4.x compat)."""
host: str
priority: int
ttl: int
@dataclass(frozen=True, slots=True)
class AresQueryNSResult:
"""NS record result (pycares 4.x compat)."""
host: str
ttl: int
@dataclass(frozen=True, slots=True)
class AresQueryTXTResult:
"""TXT record result (pycares 4.x compat)."""
text: str | bytes # str if ASCII, bytes otherwise (pycares 4.x behavior)
ttl: int
@dataclass(frozen=True, slots=True)
class AresQuerySOAResult:
"""SOA record result (pycares 4.x compat)."""
nsname: str
hostmaster: str
serial: int
refresh: int
retry: int
expires: int
minttl: int
ttl: int
@dataclass(frozen=True, slots=True)
class AresQuerySRVResult:
"""SRV record result (pycares 4.x compat)."""
host: str
port: int
priority: int
weight: int
ttl: int
@dataclass(frozen=True, slots=True)
class AresQueryNAPTRResult:
"""NAPTR record result (pycares 4.x compat)."""
order: int
preference: int
flags: str
service: str
regex: str
replacement: str
ttl: int
@dataclass(frozen=True, slots=True)
class AresQueryCAAResult:
"""CAA record result (pycares 4.x compat)."""
critical: int
property: str
value: str
ttl: int
@dataclass(frozen=True, slots=True)
class AresQueryPTRResult:
"""PTR record result (pycares 4.x compat)."""
name: str
ttl: int
aliases: list[str]
@dataclass(frozen=True, slots=True)
class AresHostResult:
"""Host result (compatible with pycares 4.x ares_host_result)."""
name: str
aliases: list[str]
addresses: list[str]
# Type alias for a single converted record
ConvertedRecord = Union[
AresQueryAResult,
AresQueryAAAAResult,
AresQueryCNAMEResult,
AresQueryMXResult,
AresQueryNSResult,
AresQueryTXTResult,
AresQuerySOAResult,
AresQuerySRVResult,
AresQueryNAPTRResult,
AresQueryCAAResult,
AresQueryPTRResult,
pycares.DNSRecord, # Unknown types returned as-is
]
# Type alias for query results
QueryResult = Union[
list[AresQueryAResult],
list[AresQueryAAAAResult],
AresQueryCNAMEResult,
list[AresQueryMXResult],
list[AresQueryNSResult],
list[AresQueryTXTResult],
AresQuerySOAResult,
list[AresQuerySRVResult],
list[AresQueryNAPTRResult],
list[AresQueryCAAResult],
AresQueryPTRResult,
list[ConvertedRecord], # For ANY query type
]
def _convert_record(record: pycares.DNSRecord) -> ConvertedRecord:
"""Convert a single DNS record to pycares 4.x compatible format."""
ttl = record.ttl
record_type = record.type
if record_type == pycares.QUERY_TYPE_A:
a_data = cast(pycares.ARecordData, record.data)
return AresQueryAResult(host=a_data.addr, ttl=ttl)
if record_type == pycares.QUERY_TYPE_AAAA:
aaaa_data = cast(pycares.AAAARecordData, record.data)
return AresQueryAAAAResult(host=aaaa_data.addr, ttl=ttl)
if record_type == pycares.QUERY_TYPE_CNAME:
cname_data = cast(pycares.CNAMERecordData, record.data)
return AresQueryCNAMEResult(cname=cname_data.cname, ttl=ttl)
if record_type == pycares.QUERY_TYPE_MX:
mx_data = cast(pycares.MXRecordData, record.data)
return AresQueryMXResult(
host=mx_data.exchange, priority=mx_data.priority, ttl=ttl
)
if record_type == pycares.QUERY_TYPE_NS:
ns_data = cast(pycares.NSRecordData, record.data)
return AresQueryNSResult(host=ns_data.nsdname, ttl=ttl)
if record_type == pycares.QUERY_TYPE_TXT:
txt_data = cast(pycares.TXTRecordData, record.data)
return AresQueryTXTResult(text=_maybe_str(txt_data.data), ttl=ttl)
if record_type == pycares.QUERY_TYPE_SOA:
soa_data = cast(pycares.SOARecordData, record.data)
return AresQuerySOAResult(
nsname=soa_data.mname,
hostmaster=soa_data.rname,
serial=soa_data.serial,
refresh=soa_data.refresh,
retry=soa_data.retry,
expires=soa_data.expire,
minttl=soa_data.minimum,
ttl=ttl,
)
if record_type == pycares.QUERY_TYPE_SRV:
srv_data = cast(pycares.SRVRecordData, record.data)
return AresQuerySRVResult(
host=srv_data.target,
port=srv_data.port,
priority=srv_data.priority,
weight=srv_data.weight,
ttl=ttl,
)
if record_type == pycares.QUERY_TYPE_NAPTR:
naptr_data = cast(pycares.NAPTRRecordData, record.data)
return AresQueryNAPTRResult(
order=naptr_data.order,
preference=naptr_data.preference,
flags=naptr_data.flags,
service=naptr_data.service,
regex=naptr_data.regexp,
replacement=naptr_data.replacement,
ttl=ttl,
)
if record_type == pycares.QUERY_TYPE_CAA:
caa_data = cast(pycares.CAARecordData, record.data)
return AresQueryCAAResult(
critical=caa_data.critical,
property=caa_data.tag,
value=caa_data.value,
ttl=ttl,
)
if record_type == pycares.QUERY_TYPE_PTR:
ptr_data = cast(pycares.PTRRecordData, record.data)
return AresQueryPTRResult(name=ptr_data.dname, ttl=ttl, aliases=[])
# Return raw record for unknown types
return record
def convert_result(dns_result: pycares.DNSResult, qtype: int) -> QueryResult:
"""Convert pycares 5.x DNSResult to pycares 4.x compatible format."""
# For ANY - convert all records and return mixed list
if qtype == pycares.QUERY_TYPE_ANY:
return [_convert_record(record) for record in dns_result.answer]
results: list[ConvertedRecord] = []
for record in dns_result.answer:
record_type = record.type
# Filter by query type since answer can contain other types
# (e.g., CNAME records when querying for A/AAAA)
if record_type != qtype:
continue
converted = _convert_record(record)
# CNAME, SOA, and PTR return single result, not list
if record_type in _SINGLE_RESULT_QTYPES:
return cast(QueryResult, converted)
results.append(converted)
# NOERROR/NODATA: c-ares delivered ARES_SUCCESS but the answer has no
# records of the queried type. pycares 4.x raised ARES_ENODATA here;
# without this branch single-result qtypes (CNAME/SOA/PTR) would
# resolve to [] and crash callers reading .name/.cname/.nsname.
if not results:
raise error.DNSError(
pycares.errno.ARES_ENODATA,
pycares.errno.strerror(pycares.errno.ARES_ENODATA),
)
return results

View File

@ -0,0 +1,62 @@
from pycares.errno import (
ARES_EADDRGETNETWORKPARAMS,
ARES_EBADFAMILY,
ARES_EBADFLAGS,
ARES_EBADHINTS,
ARES_EBADNAME,
ARES_EBADQUERY,
ARES_EBADRESP,
ARES_EBADSTR,
ARES_ECANCELLED,
ARES_ECONNREFUSED,
ARES_EDESTRUCTION,
ARES_EFILE,
ARES_EFORMERR,
ARES_ELOADIPHLPAPI,
ARES_ENODATA,
ARES_ENOMEM,
ARES_ENONAME,
ARES_ENOTFOUND,
ARES_ENOTIMP,
ARES_ENOTINITIALIZED,
ARES_EOF,
ARES_EREFUSED,
ARES_ESERVFAIL,
ARES_ESERVICE,
ARES_ETIMEOUT,
ARES_SUCCESS,
)
__all__ = [
'ARES_EADDRGETNETWORKPARAMS',
'ARES_EBADFAMILY',
'ARES_EBADFLAGS',
'ARES_EBADHINTS',
'ARES_EBADNAME',
'ARES_EBADQUERY',
'ARES_EBADRESP',
'ARES_EBADSTR',
'ARES_ECANCELLED',
'ARES_ECONNREFUSED',
'ARES_EDESTRUCTION',
'ARES_EFILE',
'ARES_EFORMERR',
'ARES_ELOADIPHLPAPI',
'ARES_ENODATA',
'ARES_ENOMEM',
'ARES_ENONAME',
'ARES_ENOTFOUND',
'ARES_ENOTIMP',
'ARES_ENOTINITIALIZED',
'ARES_EOF',
'ARES_EREFUSED',
'ARES_ESERVFAIL',
'ARES_ESERVICE',
'ARES_ETIMEOUT',
'ARES_SUCCESS',
'DNSError',
]
class DNSError(Exception):
"""Base class for all DNS errors."""

View File

@ -0,0 +1,123 @@
Metadata-Version: 2.4
Name: aiohappyeyeballs
Version: 2.6.2
Summary: Happy Eyeballs for asyncio
License: PSF-2.0
License-File: LICENSE
Author: J. Nick Koston
Author-email: nick@koston.org
Requires-Python: >=3.10
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Libraries
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: License :: OSI Approved :: Python Software Foundation License
Project-URL: Bug Tracker, https://github.com/aio-libs/aiohappyeyeballs/issues
Project-URL: Changelog, https://github.com/aio-libs/aiohappyeyeballs/blob/main/CHANGELOG.md
Project-URL: Documentation, https://aiohappyeyeballs.readthedocs.io
Project-URL: Repository, https://github.com/aio-libs/aiohappyeyeballs
Description-Content-Type: text/markdown
# aiohappyeyeballs
<p align="center">
<a href="https://github.com/aio-libs/aiohappyeyeballs/actions/workflows/ci.yml?query=branch%3Amain">
<img src="https://img.shields.io/github/actions/workflow/status/aio-libs/aiohappyeyeballs/ci-cd.yml?branch=main&label=CI&logo=github&style=flat-square" alt="CI Status" >
</a>
<a href="https://aiohappyeyeballs.readthedocs.io">
<img src="https://img.shields.io/readthedocs/aiohappyeyeballs.svg?logo=read-the-docs&logoColor=fff&style=flat-square" alt="Documentation Status">
</a>
<a href="https://codecov.io/gh/aio-libs/aiohappyeyeballs">
<img src="https://img.shields.io/codecov/c/github/aio-libs/aiohappyeyeballs.svg?logo=codecov&logoColor=fff&style=flat-square" alt="Test coverage percentage">
</a>
</p>
<p align="center">
<a href="https://python-poetry.org/">
<img src="https://img.shields.io/badge/packaging-poetry-299bd7?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAASCAYAAABrXO8xAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAJJSURBVHgBfZLPa1NBEMe/s7tNXoxW1KJQKaUHkXhQvHgW6UHQQ09CBS/6V3hKc/AP8CqCrUcpmop3Cx48eDB4yEECjVQrlZb80CRN8t6OM/teagVxYZi38+Yz853dJbzoMV3MM8cJUcLMSUKIE8AzQ2PieZzFxEJOHMOgMQQ+dUgSAckNXhapU/NMhDSWLs1B24A8sO1xrN4NECkcAC9ASkiIJc6k5TRiUDPhnyMMdhKc+Zx19l6SgyeW76BEONY9exVQMzKExGKwwPsCzza7KGSSWRWEQhyEaDXp6ZHEr416ygbiKYOd7TEWvvcQIeusHYMJGhTwF9y7sGnSwaWyFAiyoxzqW0PM/RjghPxF2pWReAowTEXnDh0xgcLs8l2YQmOrj3N7ByiqEoH0cARs4u78WgAVkoEDIDoOi3AkcLOHU60RIg5wC4ZuTC7FaHKQm8Hq1fQuSOBvX/sodmNJSB5geaF5CPIkUeecdMxieoRO5jz9bheL6/tXjrwCyX/UYBUcjCaWHljx1xiX6z9xEjkYAzbGVnB8pvLmyXm9ep+W8CmsSHQQY77Zx1zboxAV0w7ybMhQmfqdmmw3nEp1I0Z+FGO6M8LZdoyZnuzzBdjISicKRnpxzI9fPb+0oYXsNdyi+d3h9bm9MWYHFtPeIZfLwzmFDKy1ai3p+PDls1Llz4yyFpferxjnyjJDSEy9CaCx5m2cJPerq6Xm34eTrZt3PqxYO1XOwDYZrFlH1fWnpU38Y9HRze3lj0vOujZcXKuuXm3jP+s3KbZVra7y2EAAAAAASUVORK5CYII=" alt="Poetry">
</a>
<a href="https://github.com/astral-sh/ruff">
<img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json" alt="Ruff">
</a>
<a href="https://github.com/pre-commit/pre-commit">
<img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=flat-square" alt="pre-commit">
</a>
</p>
<p align="center">
<a href="https://pypi.org/project/aiohappyeyeballs/">
<img src="https://img.shields.io/pypi/v/aiohappyeyeballs.svg?logo=python&logoColor=fff&style=flat-square" alt="PyPI Version">
</a>
<img src="https://img.shields.io/pypi/pyversions/aiohappyeyeballs.svg?style=flat-square&logo=python&amp;logoColor=fff" alt="Supported Python versions">
<img src="https://img.shields.io/pypi/l/aiohappyeyeballs.svg?style=flat-square" alt="License">
</p>
---
**Documentation**: <a href="https://aiohappyeyeballs.readthedocs.io" target="_blank">https://aiohappyeyeballs.readthedocs.io </a>
**Source Code**: <a href="https://github.com/aio-libs/aiohappyeyeballs" target="_blank">https://github.com/aio-libs/aiohappyeyeballs </a>
---
[Happy Eyeballs](https://en.wikipedia.org/wiki/Happy_Eyeballs)
([RFC 8305](https://www.rfc-editor.org/rfc/rfc8305.html))
## Use case
This library exists to allow connecting with
[Happy Eyeballs](https://en.wikipedia.org/wiki/Happy_Eyeballs)
([RFC 8305](https://www.rfc-editor.org/rfc/rfc8305.html))
when you
already have a list of addrinfo and not a DNS name.
The stdlib version of `loop.create_connection()`
will only work when you pass in an unresolved name which
is not a good fit when using DNS caching or resolving
names via another method such as `zeroconf`.
## Installation
Install this via pip (or your favourite package manager):
`pip install aiohappyeyeballs`
## License
[aiohappyeyeballs is licensed under the same terms as cpython itself.](https://github.com/python/cpython/blob/main/LICENSE)
## Example usage
```python
addr_infos = await loop.getaddrinfo("example.org", 80)
socket = await start_connection(addr_infos)
socket = await start_connection(addr_infos, local_addr_infos=local_addr_infos, happy_eyeballs_delay=0.2)
transport, protocol = await loop.create_connection(
MyProtocol, sock=socket, ...)
# Remove the first address for each family from addr_info
pop_addr_infos_interleave(addr_info, 1)
# Remove all matching address from addr_info
remove_addr_infos(addr_info, "dead::beef::")
# Convert a local_addr to local_addr_infos
local_addr_infos = addr_to_addr_infos(("127.0.0.1",0))
```
## Credits
This package contains code from cpython and is licensed under the same terms as cpython itself.
This package was created with
[Copier](https://copier.readthedocs.io/) and the
[browniebroke/pypackage-template](https://github.com/browniebroke/pypackage-template)
project template.

View File

@ -0,0 +1,16 @@
aiohappyeyeballs-2.6.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
aiohappyeyeballs-2.6.2.dist-info/METADATA,sha256=cqs2VY8TwE2e_4qqnW409Si3suvj-aM-8dCiWG2Angk,5888
aiohappyeyeballs-2.6.2.dist-info/RECORD,,
aiohappyeyeballs-2.6.2.dist-info/WHEEL,sha256=EGEvSphFYqXKs23-kQBeyNoJP1nrT8ZJKQoi5p5DYL8,88
aiohappyeyeballs-2.6.2.dist-info/licenses/LICENSE,sha256=Oy-B_iHRgcSZxZolbI4ZaEVdZonSaaqFNzv7avQdo78,13936
aiohappyeyeballs/__init__.py,sha256=Af9ADZj3BWLfGaA7ITOFPlKIenh3ozSNWL3yezSZ2Jw,361
aiohappyeyeballs/__pycache__/__init__.cpython-312.pyc,,
aiohappyeyeballs/__pycache__/_staggered.cpython-312.pyc,,
aiohappyeyeballs/__pycache__/impl.cpython-312.pyc,,
aiohappyeyeballs/__pycache__/types.cpython-312.pyc,,
aiohappyeyeballs/__pycache__/utils.cpython-312.pyc,,
aiohappyeyeballs/_staggered.py,sha256=aj3cSwHEDX88UMfO9bUau9tfrRAszhjg99dpEMiAOGM,6698
aiohappyeyeballs/impl.py,sha256=TIkAK4xfACvKBp1s7DAKSobHefUTOC2HGE-n0tOthRk,9667
aiohappyeyeballs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
aiohappyeyeballs/types.py,sha256=_8JmHFix6MeM1e7hRP7BleEaGy93GswGtzQv068zKY8,288
aiohappyeyeballs/utils.py,sha256=dPAcNcrU_VhaTolTEEA94hgh9ONDN9_dYT4Xo9ORqQw,2922

View File

@ -0,0 +1,4 @@
Wheel-Version: 1.0
Generator: poetry-core 2.4.0
Root-Is-Purelib: true
Tag: py3-none-any

View File

@ -0,0 +1,279 @@
A. HISTORY OF THE SOFTWARE
==========================
Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
as a successor of a language called ABC. Guido remains Python's
principal author, although it includes many contributions from others.
In 1995, Guido continued his work on Python at the Corporation for
National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
in Reston, Virginia where he released several versions of the
software.
In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
year, the PythonLabs team moved to Digital Creations, which became
Zope Corporation. In 2001, the Python Software Foundation (PSF, see
https://www.python.org/psf/) was formed, a non-profit organization
created specifically to own Python-related Intellectual Property.
Zope Corporation was a sponsoring member of the PSF.
All Python releases are Open Source (see https://opensource.org for
the Open Source Definition). Historically, most, but not all, Python
releases have also been GPL-compatible; the table below summarizes
the various releases.
Release Derived Year Owner GPL-
from compatible? (1)
0.9.0 thru 1.2 1991-1995 CWI yes
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
1.6 1.5.2 2000 CNRI no
2.0 1.6 2000 BeOpen.com no
1.6.1 1.6 2001 CNRI yes (2)
2.1 2.0+1.6.1 2001 PSF no
2.0.1 2.0+1.6.1 2001 PSF yes
2.1.1 2.1+2.0.1 2001 PSF yes
2.1.2 2.1.1 2002 PSF yes
2.1.3 2.1.2 2002 PSF yes
2.2 and above 2.1.1 2001-now PSF yes
Footnotes:
(1) GPL-compatible doesn't mean that we're distributing Python under
the GPL. All Python licenses, unlike the GPL, let you distribute
a modified version without making your changes open source. The
GPL-compatible licenses make it possible to combine Python with
other software that is released under the GPL; the others don't.
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
because its license has a choice of law clause. According to
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
is "not incompatible" with the GPL.
Thanks to the many outside volunteers who have worked under Guido's
direction to make these releases possible.
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
===============================================================
Python software and documentation are licensed under the
Python Software Foundation License Version 2.
Starting with Python 3.8.6, examples, recipes, and other code in
the documentation are dual licensed under the PSF License Version 2
and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses.
The licenses are listed with code falling under that license.
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
--------------------------------------------
1. This LICENSE AGREEMENT is between the Python Software Foundation
("PSF"), and the Individual or Organization ("Licensee") accessing and
otherwise using this software ("Python") in source or binary form and
its associated documentation.
2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python alone or in any derivative version,
provided, however, that PSF's License Agreement and PSF's notice of copyright,
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation;
All Rights Reserved" are retained in Python alone or in any derivative version
prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python.
4. PSF is making Python available to Licensee on an "AS IS"
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any
relationship of agency, partnership, or joint venture between PSF and
Licensee. This License Agreement does not grant permission to use PSF
trademarks or trade name in a trademark sense to endorse or promote
products or services of Licensee, or any third party.
8. By copying, installing or otherwise using Python, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
-------------------------------------------
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
Individual or Organization ("Licensee") accessing and otherwise using
this software in source or binary form and its associated
documentation ("the Software").
2. Subject to the terms and conditions of this BeOpen Python License
Agreement, BeOpen hereby grants Licensee a non-exclusive,
royalty-free, world-wide license to reproduce, analyze, test, perform
and/or display publicly, prepare derivative works, distribute, and
otherwise use the Software alone or in any derivative version,
provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an "AS IS"
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all
respects by the law of the State of California, excluding conflict of
law provisions. Nothing in this License Agreement shall be deemed to
create any relationship of agency, partnership, or joint venture
between BeOpen and Licensee. This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark
sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the "BeOpen Python" logos available at
http://www.pythonlabs.com/logos.html may be used according to the
permissions granted on that web page.
7. By copying, installing or otherwise using the software, Licensee
agrees to be bound by the terms and conditions of this License
Agreement.
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
---------------------------------------
1. This LICENSE AGREEMENT is between the Corporation for National
Research Initiatives, having an office at 1895 Preston White Drive,
Reston, VA 20191 ("CNRI"), and the Individual or Organization
("Licensee") accessing and otherwise using Python 1.6.1 software in
source or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, CNRI
hereby grants Licensee a nonexclusive, royalty-free, world-wide
license to reproduce, analyze, test, perform and/or display publicly,
prepare derivative works, distribute, and otherwise use Python 1.6.1
alone or in any derivative version, provided, however, that CNRI's
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
1995-2001 Corporation for National Research Initiatives; All Rights
Reserved" are retained in Python 1.6.1 alone or in any derivative
version prepared by Licensee. Alternately, in lieu of CNRI's License
Agreement, Licensee may substitute the following text (omitting the
quotes): "Python 1.6.1 is made available subject to the terms and
conditions in CNRI's License Agreement. This Agreement together with
Python 1.6.1 may be located on the internet using the following
unique, persistent identifier (known as a handle): 1895.22/1013. This
Agreement may also be obtained from a proxy server on the internet
using the following URL: http://hdl.handle.net/1895.22/1013".
3. In the event Licensee prepares a derivative work that is based on
or incorporates Python 1.6.1 or any part thereof, and wants to make
the derivative work available to others as provided herein, then
Licensee hereby agrees to include in any such work a brief summary of
the changes made to Python 1.6.1.
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material
breach of its terms and conditions.
7. This License Agreement shall be governed by the federal
intellectual property law of the United States, including without
limitation the federal copyright law, and, to the extent such
U.S. federal law does not apply, by the law of the Commonwealth of
Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based
on Python 1.6.1 that incorporate non-separable material that was
previously distributed under the GNU General Public License (GPL), the
law of the Commonwealth of Virginia shall govern this License
Agreement only as to issues arising under or with respect to
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between CNRI and Licensee. This
License Agreement does not grant permission to use CNRI trademarks or
trade name in a trademark sense to endorse or promote products or
services of Licensee, or any third party.
8. By clicking on the "ACCEPT" button where indicated, or by copying,
installing or otherwise using Python 1.6.1, Licensee agrees to be
bound by the terms and conditions of this License Agreement.
ACCEPT
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
--------------------------------------------------
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
The Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
----------------------------------------------------------------------
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

View File

@ -0,0 +1,14 @@
__version__ = "2.6.2"
from .impl import start_connection
from .types import AddrInfoType, SocketFactoryType
from .utils import addr_to_addr_infos, pop_addr_infos_interleave, remove_addr_infos
__all__ = (
"AddrInfoType",
"SocketFactoryType",
"addr_to_addr_infos",
"pop_addr_infos_interleave",
"remove_addr_infos",
"start_connection",
)

View File

@ -0,0 +1,197 @@
import asyncio
import contextlib
from collections.abc import Awaitable, Callable, Iterable
from typing import (
TYPE_CHECKING,
Any,
TypeVar,
)
_T = TypeVar("_T")
RE_RAISE_EXCEPTIONS = (SystemExit, KeyboardInterrupt)
def _set_result(wait_next: "asyncio.Future[None]") -> None:
"""Set the result of a future if it is not already done."""
if not wait_next.done():
wait_next.set_result(None)
async def _wait_one(
futures: "Iterable[asyncio.Future[Any]]",
loop: asyncio.AbstractEventLoop,
) -> _T:
"""Wait for the first future to complete."""
wait_next = loop.create_future()
def _on_completion(fut: "asyncio.Future[Any]") -> None:
if not wait_next.done():
wait_next.set_result(fut)
for f in futures:
f.add_done_callback(_on_completion)
try:
return await wait_next
finally:
for f in futures:
f.remove_done_callback(_on_completion)
async def staggered_race(
coro_fns: Iterable[Callable[[], Awaitable[_T]]],
delay: float | None,
*,
loop: asyncio.AbstractEventLoop | None = None,
) -> tuple[_T | None, int | None, list[BaseException | None]]:
"""
Run coroutines with staggered start times and take the first to finish.
This method takes an iterable of coroutine functions. The first one is
started immediately. From then on, whenever the immediately preceding one
fails (raises an exception), or when *delay* seconds has passed, the next
coroutine is started. This continues until one of the coroutines complete
successfully, in which case all others are cancelled, or until all
coroutines fail.
The coroutines provided should be well-behaved in the following way:
* They should only ``return`` if completed successfully.
* They should always raise an exception if they did not complete
successfully. In particular, if they handle cancellation, they should
probably reraise, like this::
try:
# do work
except asyncio.CancelledError:
# undo partially completed work
raise
Args:
----
coro_fns: an iterable of coroutine functions, i.e. callables that
return a coroutine object when called. Use ``functools.partial`` or
lambdas to pass arguments.
delay: amount of time, in seconds, between starting coroutines. If
``None``, the coroutines will run sequentially.
loop: the event loop to use. If ``None``, the running loop is used.
Returns:
-------
tuple *(winner_result, winner_index, exceptions)* where
- *winner_result*: the result of the winning coroutine, or ``None``
if no coroutines won.
- *winner_index*: the index of the winning coroutine in
``coro_fns``, or ``None`` if no coroutines won. If the winning
coroutine may return None on success, *winner_index* can be used
to definitively determine whether any coroutine won.
- *exceptions*: list of exceptions returned by the coroutines.
``len(exceptions)`` is equal to the number of coroutines actually
started, and the order is the same as in ``coro_fns``. The winning
coroutine's entry is ``None``.
"""
loop = loop or asyncio.get_running_loop()
exceptions: list[BaseException | None] = []
tasks: set[asyncio.Task[tuple[_T, int] | None]] = set()
async def run_one_coro(
coro_fn: Callable[[], Awaitable[_T]],
this_index: int,
start_next: "asyncio.Future[None]",
) -> tuple[_T, int] | None:
"""
Run a single coroutine.
If the coroutine fails, set the exception in the exceptions list and
start the next coroutine by setting the result of the start_next.
If the coroutine succeeds, return the result and the index of the
coroutine in the coro_fns list.
If SystemExit or KeyboardInterrupt is raised, re-raise it.
"""
try:
result = await coro_fn()
except RE_RAISE_EXCEPTIONS:
raise
except BaseException as e:
exceptions[this_index] = e
_set_result(start_next) # Kickstart the next coroutine
return None
return result, this_index
start_next_timer: asyncio.TimerHandle | None = None
start_next: asyncio.Future[None] | None
task: asyncio.Task[tuple[_T, int] | None]
done: asyncio.Future[None] | asyncio.Task[tuple[_T, int] | None]
coro_iter = iter(coro_fns)
this_index = -1
try:
while True:
if coro_fn := next(coro_iter, None):
this_index += 1
exceptions.append(None)
start_next = loop.create_future()
task = loop.create_task(run_one_coro(coro_fn, this_index, start_next))
tasks.add(task)
start_next_timer = (
loop.call_later(delay, _set_result, start_next) if delay else None
)
elif not tasks:
# We exhausted the coro_fns list and no tasks are running
# so we have no winner and all coroutines failed.
break
while tasks or start_next:
done = await _wait_one(
(*tasks, start_next) if start_next else tasks, loop
)
if done is start_next:
# The current task has failed or the timer has expired
# so we need to start the next task.
start_next = None
if start_next_timer:
start_next_timer.cancel()
start_next_timer = None
# Break out of the task waiting loop to start the next
# task.
break
if TYPE_CHECKING:
assert isinstance(done, asyncio.Task)
tasks.remove(done)
if winner := done.result():
return *winner, exceptions
finally:
# We either have:
# - a winner
# - all tasks failed
# - a KeyboardInterrupt or SystemExit.
#
# If the timer is still running, cancel it.
#
if start_next_timer:
start_next_timer.cancel()
#
# If there are any tasks left, cancel them and than
# wait them so they fill the exceptions list.
#
for task in tasks:
task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await task
return None, None, exceptions

View File

@ -0,0 +1,261 @@
"""Base implementation."""
import asyncio
import collections
import contextlib
import functools
import itertools
import socket
from collections.abc import Sequence
from . import _staggered
from .types import AddrInfoType, SocketFactoryType
async def start_connection(
addr_infos: Sequence[AddrInfoType],
*,
local_addr_infos: Sequence[AddrInfoType] | None = None,
happy_eyeballs_delay: float | None = None,
interleave: int | None = None,
loop: asyncio.AbstractEventLoop | None = None,
socket_factory: SocketFactoryType | None = None,
) -> socket.socket:
"""
Connect to a TCP server.
Create a socket connection to a specified destination. The
destination is specified as a list of AddrInfoType tuples as
returned from getaddrinfo().
The arguments are, in order:
* ``family``: the address family, e.g. ``socket.AF_INET`` or
``socket.AF_INET6``.
* ``type``: the socket type, e.g. ``socket.SOCK_STREAM`` or
``socket.SOCK_DGRAM``.
* ``proto``: the protocol, e.g. ``socket.IPPROTO_TCP`` or
``socket.IPPROTO_UDP``.
* ``canonname``: the canonical name of the address, e.g.
``"www.python.org"``.
* ``sockaddr``: the socket address
This method is a coroutine which will try to establish the connection
in the background. When successful, the coroutine returns a
socket.
The expected use case is to use this method in conjunction with
loop.create_connection() to establish a connection to a server::
socket = await start_connection(addr_infos)
transport, protocol = await loop.create_connection(
MyProtocol, sock=socket, ...)
"""
if not addr_infos:
raise ValueError("addr_infos must not be empty")
current_loop = loop or asyncio.get_running_loop()
single_addr_info = len(addr_infos) == 1
if happy_eyeballs_delay is not None and interleave is None:
# If using happy eyeballs, default to interleave addresses by family
interleave = 1
if interleave and not single_addr_info:
addr_infos = _interleave_addrinfos(addr_infos, interleave)
sock: socket.socket | None = None
# uvloop can raise RuntimeError instead of OSError
exceptions: list[list[OSError | RuntimeError]] = []
if happy_eyeballs_delay is None or single_addr_info:
# not using happy eyeballs
for addrinfo in addr_infos:
try:
sock = await _connect_sock(
current_loop,
exceptions,
addrinfo,
local_addr_infos,
None,
socket_factory,
)
break
except (RuntimeError, OSError):
continue
else: # using happy eyeballs
open_sockets: set[socket.socket] = set()
try:
sock, _, _ = await _staggered.staggered_race(
(
functools.partial(
_connect_sock,
current_loop,
exceptions,
addrinfo,
local_addr_infos,
open_sockets,
socket_factory,
)
for addrinfo in addr_infos
),
happy_eyeballs_delay,
)
finally:
# If we have a winner, staggered_race will
# cancel the other tasks, however there is a
# small race window where any of the other tasks
# can be done before they are cancelled which
# will leave the socket open. To avoid this problem
# we pass a set to _connect_sock to keep track of
# the open sockets and close them here if there
# are any "runner up" sockets.
for s in open_sockets:
if s is not sock:
with contextlib.suppress(OSError):
s.close()
open_sockets = None # type: ignore[assignment]
if sock is None:
all_exceptions = [exc for sub in exceptions for exc in sub]
try:
first_exception = all_exceptions[0]
if len(all_exceptions) == 1:
raise first_exception
else:
# If they all have the same str(), raise one.
model = str(first_exception)
if all(str(exc) == model for exc in all_exceptions):
raise first_exception
# Raise a combined exception so the user can see all
# the various error messages.
msg = "Multiple exceptions: {}".format(
", ".join(str(exc) for exc in all_exceptions)
)
# If the errno is the same for all exceptions, raise
# an OSError with that errno.
if isinstance(first_exception, OSError):
first_errno = first_exception.errno
if all(
isinstance(exc, OSError) and exc.errno == first_errno
for exc in all_exceptions
):
raise OSError(first_errno, msg)
elif isinstance(first_exception, RuntimeError) and all(
isinstance(exc, RuntimeError) for exc in all_exceptions
):
raise RuntimeError(msg)
# We have a mix of OSError and RuntimeError
# so we have to pick which one to raise.
# and we raise OSError for compatibility
raise OSError(msg)
finally:
all_exceptions = None # type: ignore[assignment]
exceptions = None # type: ignore[assignment]
return sock
async def _connect_sock(
loop: asyncio.AbstractEventLoop,
exceptions: list[list[OSError | RuntimeError]],
addr_info: AddrInfoType,
local_addr_infos: Sequence[AddrInfoType] | None = None,
open_sockets: set[socket.socket] | None = None,
socket_factory: SocketFactoryType | None = None,
) -> socket.socket:
"""
Create, bind and connect one socket.
If open_sockets is passed, add the socket to the set of open sockets.
Any failure caught here will remove the socket from the set and close it.
Callers can use this set to close any sockets that are not the winner
of all staggered tasks in the result there are runner up sockets aka
multiple winners.
"""
my_exceptions: list[OSError | RuntimeError] = []
exceptions.append(my_exceptions)
family, type_, proto, _, address = addr_info
sock = None
try:
if socket_factory is not None:
sock = socket_factory(addr_info)
else:
sock = socket.socket(family=family, type=type_, proto=proto)
if open_sockets is not None:
open_sockets.add(sock)
sock.setblocking(False)
if local_addr_infos is not None:
for lfamily, _, _, _, laddr in local_addr_infos:
# skip local addresses of different family
if lfamily != family:
continue
try:
sock.bind(laddr)
break
except OSError as exc:
msg = (
f"error while attempting to bind on "
f"address {laddr!r}: "
f"{(exc.strerror or '').lower()}"
)
exc = OSError(exc.errno, msg)
my_exceptions.append(exc)
else: # all bind attempts failed
if my_exceptions:
raise my_exceptions.pop()
else:
raise OSError(f"no matching local address with {family=} found")
await loop.sock_connect(sock, address)
return sock
except (RuntimeError, OSError) as exc:
my_exceptions.append(exc)
if sock is not None:
if open_sockets is not None:
open_sockets.remove(sock)
try:
sock.close()
except OSError as e:
my_exceptions.append(e)
raise
raise
except:
if sock is not None:
if open_sockets is not None:
open_sockets.remove(sock)
try:
sock.close()
except OSError as e:
my_exceptions.append(e)
raise
raise
finally:
exceptions = my_exceptions = None # type: ignore[assignment]
def _interleave_addrinfos(
addrinfos: Sequence[AddrInfoType], first_address_family_count: int = 1
) -> list[AddrInfoType]:
"""Interleave list of addrinfo tuples by family."""
# Group addresses by family
addrinfos_by_family: collections.OrderedDict[int, list[AddrInfoType]] = (
collections.OrderedDict()
)
for addr in addrinfos:
family = addr[0]
if family not in addrinfos_by_family:
addrinfos_by_family[family] = []
addrinfos_by_family[family].append(addr)
addrinfos_lists = list(addrinfos_by_family.values())
reordered: list[AddrInfoType] = []
if first_address_family_count > 1:
reordered.extend(addrinfos_lists[0][: first_address_family_count - 1])
del addrinfos_lists[0][: first_address_family_count - 1]
reordered.extend(
a
for a in itertools.chain.from_iterable(itertools.zip_longest(*addrinfos_lists))
if a is not None
)
return reordered

View File

@ -0,0 +1,14 @@
"""Types for aiohappyeyeballs."""
import socket
from collections.abc import Callable
AddrInfoType = tuple[
int | socket.AddressFamily,
int | socket.SocketKind,
int,
str,
tuple, # type: ignore[type-arg]
]
SocketFactoryType = Callable[[AddrInfoType], socket.socket]

View File

@ -0,0 +1,92 @@
"""Utility functions for aiohappyeyeballs."""
import ipaddress
import socket
from .types import AddrInfoType
def addr_to_addr_infos(
addr: tuple[str, int, int, int] | tuple[str, int, int] | tuple[str, int] | None,
) -> list[AddrInfoType] | None:
"""Convert an address tuple to a list of addr_info tuples."""
if addr is None:
return None
host = addr[0]
port = addr[1]
is_ipv6 = ":" in host
if is_ipv6:
flowinfo = 0
scopeid = 0
addr_len = len(addr)
if addr_len >= 4:
scopeid = addr[3] # type: ignore[misc]
if addr_len >= 3:
flowinfo = addr[2] # type: ignore[misc]
addr = (host, port, flowinfo, scopeid)
family = socket.AF_INET6
else:
addr = (host, port)
family = socket.AF_INET
return [(family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", addr)]
def pop_addr_infos_interleave(
addr_infos: list[AddrInfoType], interleave: int | None = None
) -> None:
"""
Pop addr_info from the list of addr_infos by family up to interleave times.
The interleave parameter is used to know how many addr_infos for
each family should be popped of the top of the list.
"""
seen: dict[int, int] = {}
if interleave is None:
interleave = 1
to_remove: list[AddrInfoType] = []
for addr_info in addr_infos:
family = addr_info[0]
if family not in seen:
seen[family] = 0
if seen[family] < interleave:
to_remove.append(addr_info)
seen[family] += 1
for addr_info in to_remove:
addr_infos.remove(addr_info)
def _addr_tuple_to_ip_address(
addr: tuple[str, int] | tuple[str, int, int, int],
) -> tuple[ipaddress.IPv4Address, int] | tuple[ipaddress.IPv6Address, int, int, int]:
"""Convert an address tuple to an IPv4Address."""
return (ipaddress.ip_address(addr[0]), *addr[1:])
def remove_addr_infos(
addr_infos: list[AddrInfoType],
addr: tuple[str, int] | tuple[str, int, int, int],
) -> None:
"""
Remove an address from the list of addr_infos.
The addr value is typically the return value of
sock.getpeername().
"""
bad_addrs_infos: list[AddrInfoType] = []
for addr_info in addr_infos:
if addr_info[-1] == addr:
bad_addrs_infos.append(addr_info)
if bad_addrs_infos:
for bad_addr_info in bad_addrs_infos:
addr_infos.remove(bad_addr_info)
return
# Slow path in case addr is formatted differently
match_addr = _addr_tuple_to_ip_address(addr)
for addr_info in addr_infos:
if match_addr == _addr_tuple_to_ip_address(addr_info[-1]):
bad_addrs_infos.append(addr_info)
if bad_addrs_infos:
for bad_addr_info in bad_addrs_infos:
addr_infos.remove(bad_addr_info)
return
raise ValueError(f"Address {addr} not found in addr_infos")

View File

@ -0,0 +1,257 @@
Metadata-Version: 2.4
Name: aiohttp
Version: 3.14.1
Summary: Async http client/server framework (asyncio)
Maintainer-email: aiohttp team <team@aiohttp.org>
License: Apache-2.0 AND MIT
Project-URL: Homepage, https://github.com/aio-libs/aiohttp
Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org
Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org
Project-URL: CI: GitHub Actions, https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI
Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiohttp
Project-URL: Docs: Changelog, https://docs.aiohttp.org/en/stable/changes.html
Project-URL: Docs: RTD, https://docs.aiohttp.org
Project-URL: GitHub: issues, https://github.com/aio-libs/aiohttp/issues
Project-URL: GitHub: repo, https://github.com/aio-libs/aiohttp
Classifier: Development Status :: 5 - Production/Stable
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: POSIX
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP
Requires-Python: >=3.10
Description-Content-Type: text/x-rst
License-File: LICENSE.txt
License-File: vendor/llhttp/LICENSE
Requires-Dist: aiohappyeyeballs>=2.5.0
Requires-Dist: aiosignal>=1.4.0
Requires-Dist: async-timeout<6.0,>=4.0; python_version < "3.11"
Requires-Dist: attrs>=17.3.0
Requires-Dist: frozenlist>=1.1.1
Requires-Dist: multidict<7.0,>=4.5
Requires-Dist: propcache>=0.2.0
Requires-Dist: typing_extensions>=4.4; python_version < "3.13"
Requires-Dist: yarl<2.0,>=1.17.0
Provides-Extra: speedups
Requires-Dist: aiodns>=3.3.0; (sys_platform != "android" and sys_platform != "ios") and extra == "speedups"
Requires-Dist: Brotli>=1.2; (platform_python_implementation == "CPython" and sys_platform != "android" and sys_platform != "ios") and extra == "speedups"
Requires-Dist: brotlicffi>=1.2; platform_python_implementation != "CPython" and extra == "speedups"
Requires-Dist: backports.zstd; (platform_python_implementation == "CPython" and python_version < "3.14" and sys_platform != "android" and sys_platform != "ios") and extra == "speedups"
Dynamic: license-file
==================================
Async http client/server framework
==================================
.. image:: https://raw.githubusercontent.com/aio-libs/aiohttp/master/docs/aiohttp-plain.svg
:height: 64px
:width: 64px
:alt: aiohttp logo
|
.. image:: https://github.com/aio-libs/aiohttp/workflows/CI/badge.svg
:target: https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI
:alt: GitHub Actions status for master branch
.. image:: https://codecov.io/gh/aio-libs/aiohttp/branch/master/graph/badge.svg
:target: https://codecov.io/gh/aio-libs/aiohttp
:alt: codecov.io status for master branch
.. image:: https://badge.fury.io/py/aiohttp.svg
:target: https://pypi.org/project/aiohttp
:alt: Latest PyPI package version
.. image:: https://img.shields.io/pypi/dm/aiohttp
:target: https://pypistats.org/packages/aiohttp
:alt: Downloads count
.. image:: https://readthedocs.org/projects/aiohttp/badge/?version=latest
:target: https://docs.aiohttp.org/
:alt: Latest Read The Docs
.. image:: https://img.shields.io/endpoint?url=https://codspeed.io/badge.json
:target: https://codspeed.io/aio-libs/aiohttp
:alt: Codspeed.io status for aiohttp
Key Features
============
- Supports both client and server side of HTTP protocol.
- Supports both client and server Web-Sockets out-of-the-box and avoids
Callback Hell.
- Provides Web-server with middleware and pluggable routing.
Getting started
===============
Client
------
To get something from the web:
.. code-block:: python
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('http://python.org') as response:
print("Status:", response.status)
print("Content-type:", response.headers['content-type'])
html = await response.text()
print("Body:", html[:15], "...")
asyncio.run(main())
This prints:
.. code-block::
Status: 200
Content-type: text/html; charset=utf-8
Body: <!doctype html> ...
Coming from `requests <https://requests.readthedocs.io/>`_ ? Read `why we need so many lines <https://aiohttp.readthedocs.io/en/latest/http_request_lifecycle.html>`_.
Server
------
An example using a simple server:
.. code-block:: python
# examples/server_simple.py
from aiohttp import web
async def handle(request):
name = request.match_info.get('name', "Anonymous")
text = "Hello, " + name
return web.Response(text=text)
async def wshandle(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
async for msg in ws:
if msg.type == web.WSMsgType.text:
await ws.send_str("Hello, {}".format(msg.data))
elif msg.type == web.WSMsgType.binary:
await ws.send_bytes(msg.data)
elif msg.type == web.WSMsgType.close:
break
return ws
app = web.Application()
app.add_routes([web.get('/', handle),
web.get('/echo', wshandle),
web.get('/{name}', handle)])
if __name__ == '__main__':
web.run_app(app)
Documentation
=============
https://aiohttp.readthedocs.io/
Demos
=====
https://github.com/aio-libs/aiohttp-demos
External links
==============
* `Third party libraries
<http://aiohttp.readthedocs.io/en/latest/third_party.html>`_
* `Built with aiohttp
<http://aiohttp.readthedocs.io/en/latest/built_with.html>`_
* `Powered by aiohttp
<http://aiohttp.readthedocs.io/en/latest/powered_by.html>`_
Feel free to make a Pull Request for adding your link to these pages!
Communication channels
======================
*aio-libs Discussions*: https://github.com/aio-libs/aiohttp/discussions
*Matrix*: `#aio-libs:matrix.org <https://matrix.to/#/#aio-libs:matrix.org>`_
We support `Stack Overflow
<https://stackoverflow.com/questions/tagged/aiohttp>`_.
Please add *aiohttp* tag to your question there.
Requirements
============
- attrs_
- multidict_
- yarl_
- frozenlist_
Optionally you may install the aiodns_ library (highly recommended for sake of speed).
.. _aiodns: https://pypi.python.org/pypi/aiodns
.. _attrs: https://github.com/python-attrs/attrs
.. _multidict: https://pypi.python.org/pypi/multidict
.. _frozenlist: https://pypi.org/project/frozenlist/
.. _yarl: https://pypi.python.org/pypi/yarl
.. _async-timeout: https://pypi.python.org/pypi/async_timeout
Keepsafe
========
The aiohttp community would like to thank Keepsafe
(https://www.getkeepsafe.com) for its support in the early days of
the project.
Source code
===========
The latest developer version is available in a GitHub repository:
https://github.com/aio-libs/aiohttp
Benchmarks
==========
If you are interested in efficiency, the AsyncIO community maintains a
list of benchmarks on the official wiki:
https://github.com/python/asyncio/wiki/Benchmarks
--------
.. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat
:target: https://matrix.to/#/%23aio-libs:matrix.org
:alt: Matrix Room — #aio-libs:matrix.org
.. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat
:target: https://matrix.to/#/%23aio-libs-space:matrix.org
:alt: Matrix Space — #aio-libs-space:matrix.org
.. image:: https://insights.linuxfoundation.org/api/badge/health-score?project=aiohttp
:target: https://insights.linuxfoundation.org/project/aiohttp
:alt: LFX Health Score

View File

@ -0,0 +1,138 @@
aiohttp-3.14.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
aiohttp-3.14.1.dist-info/METADATA,sha256=lSrt4tDtmd7yhoDSTEq0NNoU8cSDjfDJAuOCCHWKil0,8262
aiohttp-3.14.1.dist-info/RECORD,,
aiohttp-3.14.1.dist-info/WHEEL,sha256=Tc3fF66yn9Kh-hkUUsdKQyuB9Lw0CDoeANnEbSVc3f4,190
aiohttp-3.14.1.dist-info/licenses/LICENSE.txt,sha256=Lkvl_GxMcqRm_LZl1ybgSaaJGYH-U2xPBLY2Z0lGHSM,11313
aiohttp-3.14.1.dist-info/licenses/vendor/llhttp/LICENSE,sha256=YoFo1ou1qKF-C777O9dOMm4e3CBYPXb1L0V8gskhhn0,1069
aiohttp-3.14.1.dist-info/top_level.txt,sha256=iv-JIaacmTl-hSho3QmphcKnbRRYx1st47yjz_178Ro,8
aiohttp/.hash/_cparser.pxd.hash,sha256=1xYKvgB1DahaZj6GMSLJ9qi5KmoJDD8ZPp3CIxah0ig,121
aiohttp/.hash/_find_header.pxd.hash,sha256=_mbpD6vM-CVCKq3ulUvsOAz5Wdo88wrDzfpOsMQaMNA,125
aiohttp/.hash/_http_parser.pyx.hash,sha256=D15N0PIazROldZ2ezxeuuu4VuQP9OxrN8sutpdcL6TA,125
aiohttp/.hash/_http_writer.pyx.hash,sha256=eqqhtJepEtpikWbd_gUoZOWyEBUwmHCd1fq2jfIrXSg,125
aiohttp/.hash/hdrs.py.hash,sha256=cBtTPqXxWpYN--0v2ukVWjjfVbnT3Csii1PkBJBCz8E,116
aiohttp/__init__.py,sha256=1dDCbOmlrF1FnB_LRnU-jVKY1XngQ9guX1ZasoTH-TY,8339
aiohttp/__pycache__/__init__.cpython-312.pyc,,
aiohttp/__pycache__/_cookie_helpers.cpython-312.pyc,,
aiohttp/__pycache__/abc.cpython-312.pyc,,
aiohttp/__pycache__/base_protocol.cpython-312.pyc,,
aiohttp/__pycache__/client.cpython-312.pyc,,
aiohttp/__pycache__/client_exceptions.cpython-312.pyc,,
aiohttp/__pycache__/client_middleware_digest_auth.cpython-312.pyc,,
aiohttp/__pycache__/client_middlewares.cpython-312.pyc,,
aiohttp/__pycache__/client_proto.cpython-312.pyc,,
aiohttp/__pycache__/client_reqrep.cpython-312.pyc,,
aiohttp/__pycache__/client_ws.cpython-312.pyc,,
aiohttp/__pycache__/compression_utils.cpython-312.pyc,,
aiohttp/__pycache__/connector.cpython-312.pyc,,
aiohttp/__pycache__/cookiejar.cpython-312.pyc,,
aiohttp/__pycache__/formdata.cpython-312.pyc,,
aiohttp/__pycache__/hdrs.cpython-312.pyc,,
aiohttp/__pycache__/helpers.cpython-312.pyc,,
aiohttp/__pycache__/http.cpython-312.pyc,,
aiohttp/__pycache__/http_exceptions.cpython-312.pyc,,
aiohttp/__pycache__/http_parser.cpython-312.pyc,,
aiohttp/__pycache__/http_websocket.cpython-312.pyc,,
aiohttp/__pycache__/http_writer.cpython-312.pyc,,
aiohttp/__pycache__/log.cpython-312.pyc,,
aiohttp/__pycache__/multipart.cpython-312.pyc,,
aiohttp/__pycache__/payload.cpython-312.pyc,,
aiohttp/__pycache__/payload_streamer.cpython-312.pyc,,
aiohttp/__pycache__/pytest_plugin.cpython-312.pyc,,
aiohttp/__pycache__/resolver.cpython-312.pyc,,
aiohttp/__pycache__/streams.cpython-312.pyc,,
aiohttp/__pycache__/tcp_helpers.cpython-312.pyc,,
aiohttp/__pycache__/test_utils.cpython-312.pyc,,
aiohttp/__pycache__/tracing.cpython-312.pyc,,
aiohttp/__pycache__/typedefs.cpython-312.pyc,,
aiohttp/__pycache__/web.cpython-312.pyc,,
aiohttp/__pycache__/web_app.cpython-312.pyc,,
aiohttp/__pycache__/web_exceptions.cpython-312.pyc,,
aiohttp/__pycache__/web_fileresponse.cpython-312.pyc,,
aiohttp/__pycache__/web_log.cpython-312.pyc,,
aiohttp/__pycache__/web_middlewares.cpython-312.pyc,,
aiohttp/__pycache__/web_protocol.cpython-312.pyc,,
aiohttp/__pycache__/web_request.cpython-312.pyc,,
aiohttp/__pycache__/web_response.cpython-312.pyc,,
aiohttp/__pycache__/web_routedef.cpython-312.pyc,,
aiohttp/__pycache__/web_runner.cpython-312.pyc,,
aiohttp/__pycache__/web_server.cpython-312.pyc,,
aiohttp/__pycache__/web_urldispatcher.cpython-312.pyc,,
aiohttp/__pycache__/web_ws.cpython-312.pyc,,
aiohttp/__pycache__/worker.cpython-312.pyc,,
aiohttp/_cookie_helpers.py,sha256=uOe8v5yx9N9N2JHFJiQOjuN2SiIV7D1lxnTfrXc6oEU,14092
aiohttp/_cparser.pxd,sha256=nvnwTkOaMAIazM-OUB6H66LpsNNeUG3nFxbSSLQoQEM,4336
aiohttp/_find_header.pxd,sha256=0GfwFCPN2zxEKTO1_MA5sYq2UfzsG8kcV3aTqvwlz3g,68
aiohttp/_headers.pxi,sha256=n701k28dVPjwRnx5j6LpJhLTfj7dqu2vJt7f0O60Oyg,2007
aiohttp/_http_parser.cpython-312-x86_64-linux-gnu.so,sha256=3gTnbWntd2VXGfBrHeUH3BYFoLUC_2n0WJZZ76wPR2Q,2971648
aiohttp/_http_parser.pyx,sha256=mNLUenKTRZkNlXXc9oxVDeXVJ31gsrI4XR69jrDWxPw,33860
aiohttp/_http_writer.cpython-312-x86_64-linux-gnu.so,sha256=FaMRMxE6_VwOwd6dPNhRn_7JMDsvad3qvrZNvR-OrdA,474400
aiohttp/_http_writer.pyx,sha256=FmhqRLv-qyvL2BJvVwk128VFqwYMb1b1vHLPCt3awXA,4823
aiohttp/_websocket/.hash/mask.pxd.hash,sha256=Y0zBddk_ck3pi9-BFzMcpkcvCKvwvZ4GTtZFb9u1nxQ,128
aiohttp/_websocket/.hash/mask.pyx.hash,sha256=90owpXYM8_kIma4KUcOxhWSk-Uv4NVMBoCYeFM1B3d0,128
aiohttp/_websocket/.hash/reader_c.pxd.hash,sha256=DM51AsKpHR3Bl2EIx0eUSy1uvusTDfylNeRCMT66erk,132
aiohttp/_websocket/__init__.py,sha256=Mar3R9_vBN_Ea4lsW7iTAVXD7OKswKPGqF5xgSyt77k,44
aiohttp/_websocket/__pycache__/__init__.cpython-312.pyc,,
aiohttp/_websocket/__pycache__/helpers.cpython-312.pyc,,
aiohttp/_websocket/__pycache__/models.cpython-312.pyc,,
aiohttp/_websocket/__pycache__/reader.cpython-312.pyc,,
aiohttp/_websocket/__pycache__/reader_c.cpython-312.pyc,,
aiohttp/_websocket/__pycache__/reader_py.cpython-312.pyc,,
aiohttp/_websocket/__pycache__/writer.cpython-312.pyc,,
aiohttp/_websocket/helpers.py,sha256=lMDbpiZefmHTGNxjpe6K09ZlF048KxzcOvbh-ZYqvg0,5026
aiohttp/_websocket/mask.cpython-312-x86_64-linux-gnu.so,sha256=phpHU3AXOq0nAtNgxac3ZtW2sxD-re_5ZeAl5V8lNgc,253760
aiohttp/_websocket/mask.pxd,sha256=sBmZ1Amym9kW4Ge8lj1fLZ7mPPya4LzLdpkQExQXv5M,112
aiohttp/_websocket/mask.pyx,sha256=BHjOtV0O0w7xp9p0LNADRJvGmgfPn9sGeJvSs0fL__4,1397
aiohttp/_websocket/models.py,sha256=gJLskxkUKakYFsVMdjOclSjt41rQWRCL4RfRB_wmwO0,2952
aiohttp/_websocket/reader.py,sha256=eC4qS0c5sOeQ2ebAHLaBpIaTVFaSKX79pY2xvh3Pqyw,1030
aiohttp/_websocket/reader_c.cpython-312-x86_64-linux-gnu.so,sha256=Zk-kBzozgh0cifrVwO-ZUVXRJstKqbX7_9lhy9qC_R4,1789112
aiohttp/_websocket/reader_c.pxd,sha256=l-ODGpJpOx4FxpsCtkRyITmmRvBlRo8mv87qNgeQZbo,2683
aiohttp/_websocket/reader_c.py,sha256=vf7Y6JB6hpLE17OQ39IhO70ga_DXFYksfv45M5n1wOU,20073
aiohttp/_websocket/reader_py.py,sha256=vf7Y6JB6hpLE17OQ39IhO70ga_DXFYksfv45M5n1wOU,20073
aiohttp/_websocket/writer.py,sha256=JA4ejOQMCvAvIXe_0f6uRx_aGSO4-zVUc1HJBZ125ak,11259
aiohttp/abc.py,sha256=KvpM3wDEWl_iIdNQX3NEnJf3pYAtgxynAvp5s4JkNrU,7536
aiohttp/base_protocol.py,sha256=bL6dSlNacbmln20Plez_gqYXTcFeg-V1hkHVDk4s8vU,4688
aiohttp/client.py,sha256=PzaLAKgPMytcA75z1ZIEjTBzTWR3U7wT66f38OKTwmI,64312
aiohttp/client_exceptions.py,sha256=XvJ57ppYs2IubcY3efBUkSpPElwQDqt3SWU_yssvjyI,11609
aiohttp/client_middleware_digest_auth.py,sha256=Z8ufMnBF8RQ_JaVfG3bUbAoRua_kC7RSIexQM2zm9wQ,19042
aiohttp/client_middlewares.py,sha256=kP5N9CMzQPMGPIEydeVUiLUTLsw8Vl8Gr4qAWYdu3vM,1918
aiohttp/client_proto.py,sha256=u6AZU05mZxAFG4saTaxn5lVN9vy4cmgvF9k7HQG260A,12633
aiohttp/client_reqrep.py,sha256=RWyXzuIi0NETNeuNADMbWPGd-mxcpVLsVQM0N582pU8,54704
aiohttp/client_ws.py,sha256=PiMLbWN6IBEXGiWuqL1KyQqIAydDGsWMitX_pd8cjLo,19468
aiohttp/compression_utils.py,sha256=_HTGK9dZOojGd4kyrk2A5yAt1pzVyKJh4AH5eVH0DQ8,15840
aiohttp/connector.py,sha256=0iYWUWjhc8zDYwWd-J4mtfhjojzGRRcbnQbnuwY-njU,70036
aiohttp/cookiejar.py,sha256=Y80b6_hSiDi4lN0iOb3X5983VONf-i4GhRH447gzTr0,25815
aiohttp/formdata.py,sha256=zRWW2ODYkWeahDOd-hwra-__EUizdB2bf6hAMgkCKhc,6514
aiohttp/hdrs.py,sha256=pGrWw6L6-NJqLGr8GiIQzjeaI_J5n857JqAfbOWkBkI,5106
aiohttp/helpers.py,sha256=dSbEmGl8XsLU2zwmD0dyp4wHHvHrH5TFaofkSH-OmsA,33017
aiohttp/http.py,sha256=CHXxFtOXK85RNijYkfpjvjCbKlJc3hIGRsCFAnh83hk,2077
aiohttp/http_exceptions.py,sha256=I1nyopt1sYV0GqpW2ra4pnCmFcOqMoDC4dELghEk2lI,3115
aiohttp/http_parser.py,sha256=nrXK1evVj04TjpbOu4tOx4w0yUlzG2PaEFxq0wvmfNY,45170
aiohttp/http_websocket.py,sha256=8jVNshtgNPSDnab0Dc1lAO7HFvtT7y79eZKjUXX6e28,983
aiohttp/http_writer.py,sha256=bXHXXWkEnySdYX3cCmYCFgNFsnxwPNCs-0nMjSPDRAo,12602
aiohttp/log.py,sha256=BbNKx9e3VMIm0xYjZI0IcBBoS7wjdeIeSaiJE7-qK2g,325
aiohttp/multipart.py,sha256=CJB4szZ8Zhv4htswXvSDfwY8HjlVGZFyvzGXIYo7b50,44179
aiohttp/payload.py,sha256=MXcl_K0gcblkN_YFXE_Up6N7IQwjH8uM4HTfn9Axbmg,41480
aiohttp/payload_streamer.py,sha256=PGqJKt_1ca_7i6p1UgU8jrpO1toOt5EQDQMOK9LjtV4,2225
aiohttp/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7
aiohttp/pytest_plugin.py,sha256=eGhRoy0TKNOQ3mtabkpoMgt0JThnVDr406h_kyZkQe8,12976
aiohttp/resolver.py,sha256=jmrAUnhayFdSjTsCt2_coosdVmc5RgEB5Agr65Q0sQk,9954
aiohttp/streams.py,sha256=k-XDoAfb3P8t5sHvWyEONXzYHoZ4JmJYr_aZB9CQF6c,24127
aiohttp/tcp_helpers.py,sha256=BSadqVWaBpMFDRWnhaaR941N9MiDZ7bdTrxgCb0CW-M,961
aiohttp/test_utils.py,sha256=RqqoQTTI4VpZDvOcLMmQgxisuRMCIX0qOjG019EtEpM,24636
aiohttp/tracing.py,sha256=4mokNTKdX5YuoSrvVnG4D7WTPMwe-UlYHVYxQjRv4Fw,14500
aiohttp/typedefs.py,sha256=I-V6S4T73fI_wkJfBYiL7otEeRvVHmSdsk-YYPR6Fj0,1672
aiohttp/web.py,sha256=gsyxRSPWV3iZjPUbOR3dIGcp1jm2ltBtXwkPh91co3Q,18426
aiohttp/web_app.py,sha256=hmT_DWXKwHMqmFBLE8JHhevLaaTST73ikovIIx_Tw6k,19379
aiohttp/web_exceptions.py,sha256=CsEG88dQINYSFpklCE_7bZgL1IVjHoy5dlTSVQGHPRQ,10354
aiohttp/web_fileresponse.py,sha256=5vlf-OmfgFxG5O1zGrzk-SPRkbs58izLlbQldT-DHXE,16404
aiohttp/web_log.py,sha256=lJCDsZ2xJp7HqSuijaTZyqxJ0oNWPhwxJE1FVGUWwWU,8487
aiohttp/web_middlewares.py,sha256=OIfnnCHJgRnKjzDjHoc_VzNcLuVf9y8kv5aTzM2VGvc,4152
aiohttp/web_protocol.py,sha256=RyGK7u4Lpl8yC2rSbHcKiYhSDbKSbHuA-GZTaN8q-RY,31092
aiohttp/web_request.py,sha256=o99Os7_M_C4poSc58el9q44VGO6VctJaJMFKhi7F6R8,31867
aiohttp/web_response.py,sha256=7EjxpTW4a6du5X0utXenUbSO6fbY_MgfINppJUEre-M,30783
aiohttp/web_routedef.py,sha256=S_uRfJ87LCM_fFTAIrqYTWiIqDAk0pLLYdUr1vGU9BM,6057
aiohttp/web_runner.py,sha256=PGUdZs_d2qzM3Tnb6yCQQoxfwqQZFuVr_NGIJBZq9Ms,12708
aiohttp/web_server.py,sha256=LawT47SJuLSIYgkAWL_haFgH6lVyuoD3zyFTvBatvsE,3170
aiohttp/web_urldispatcher.py,sha256=lc9Cou6tP8YJTJS2MEQWVcJV9C5dFKTyhdCLjLtkOzU,43893
aiohttp/web_ws.py,sha256=fqE-c95dxvwkZfm8M-vKeP5pCteHCmrhAdI-1o4J348,27455
aiohttp/worker.py,sha256=osuMCad7kBmL7FeR6EEEdsfkDqOaBDYvAzHMgW_hsIc,8506

View File

@ -0,0 +1,7 @@
Wheel-Version: 1.0
Generator: setuptools (82.0.1)
Root-Is-Purelib: false
Tag: cp312-cp312-manylinux_2_17_x86_64
Tag: cp312-cp312-manylinux2014_x86_64
Tag: cp312-cp312-manylinux_2_28_x86_64

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright aio-libs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,22 @@
MIT License
Copyright © 2018 Fedor Indutny
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1 @@
9ef9f04e439a30021acccf8e501e87eba2e9b0d35e506de71716d248b4284043 /home/runner/work/aiohttp/aiohttp/aiohttp/_cparser.pxd

View File

@ -0,0 +1 @@
d067f01423cddb3c442933b5fcc039b18ab651fcec1bc91c577693aafc25cf78 /home/runner/work/aiohttp/aiohttp/aiohttp/_find_header.pxd

View File

@ -0,0 +1 @@
98d2d47a729345990d9575dcf68c550de5d5277d60b2b2385d1ebd8eb0d6c4fc /home/runner/work/aiohttp/aiohttp/aiohttp/_http_parser.pyx

View File

@ -0,0 +1 @@
16686a44bbfeab2bcbd8126f570935dbc545ab060c6f56f5bc72cf0adddac170 /home/runner/work/aiohttp/aiohttp/aiohttp/_http_writer.pyx

View File

@ -0,0 +1 @@
a46ad6c3a2faf8d26a2c6afc1a2210ce379a23f2799fce7b26a01f6ce5a40642 /home/runner/work/aiohttp/aiohttp/aiohttp/hdrs.py

View File

@ -0,0 +1,279 @@
__version__ = "3.14.1"
from typing import TYPE_CHECKING
from . import hdrs as hdrs
from .client import (
BaseConnector,
ClientConnectionError,
ClientConnectionResetError,
ClientConnectorCertificateError,
ClientConnectorDNSError,
ClientConnectorError,
ClientConnectorSSLError,
ClientError,
ClientHttpProxyError,
ClientOSError,
ClientPayloadError,
ClientProxyConnectionError,
ClientRequest,
ClientResponse,
ClientResponseError,
ClientSession,
ClientSSLError,
ClientTimeout,
ClientWebSocketResponse,
ClientWSTimeout,
ConnectionTimeoutError,
ContentTypeError,
Fingerprint,
InvalidURL,
InvalidUrlClientError,
InvalidUrlRedirectClientError,
NamedPipeConnector,
NonHttpUrlClientError,
NonHttpUrlRedirectClientError,
RedirectClientError,
RequestInfo,
ServerConnectionError,
ServerDisconnectedError,
ServerFingerprintMismatch,
ServerTimeoutError,
SocketTimeoutError,
TCPConnector,
TooManyRedirects,
UnixConnector,
WSMessageTypeError,
WSServerHandshakeError,
request,
)
from .client_middleware_digest_auth import DigestAuthMiddleware
from .client_middlewares import ClientHandlerType, ClientMiddlewareType
from .compression_utils import set_zlib_backend
from .connector import (
AddrInfoType as AddrInfoType,
SocketFactoryType as SocketFactoryType,
)
from .cookiejar import CookieJar as CookieJar, DummyCookieJar as DummyCookieJar
from .formdata import FormData as FormData
from .helpers import BasicAuth, ChainMapProxy, ETag, encode_basic_auth
from .http import (
HttpVersion as HttpVersion,
HttpVersion10 as HttpVersion10,
HttpVersion11 as HttpVersion11,
WebSocketError as WebSocketError,
WSCloseCode as WSCloseCode,
WSMessage as WSMessage,
WSMsgType as WSMsgType,
)
from .multipart import (
BadContentDispositionHeader as BadContentDispositionHeader,
BadContentDispositionParam as BadContentDispositionParam,
BodyPartReader as BodyPartReader,
MultipartReader as MultipartReader,
MultipartWriter as MultipartWriter,
content_disposition_filename as content_disposition_filename,
parse_content_disposition as parse_content_disposition,
)
from .payload import (
PAYLOAD_REGISTRY as PAYLOAD_REGISTRY,
AsyncIterablePayload as AsyncIterablePayload,
BufferedReaderPayload as BufferedReaderPayload,
BytesIOPayload as BytesIOPayload,
BytesPayload as BytesPayload,
IOBasePayload as IOBasePayload,
JsonPayload as JsonPayload,
Payload as Payload,
StringIOPayload as StringIOPayload,
StringPayload as StringPayload,
TextIOPayload as TextIOPayload,
get_payload as get_payload,
payload_type as payload_type,
)
from .payload_streamer import streamer as streamer
from .resolver import (
AsyncResolver as AsyncResolver,
DefaultResolver as DefaultResolver,
ThreadedResolver as ThreadedResolver,
)
from .streams import (
EMPTY_PAYLOAD as EMPTY_PAYLOAD,
DataQueue as DataQueue,
EofStream as EofStream,
FlowControlDataQueue as FlowControlDataQueue,
StreamReader as StreamReader,
)
from .tracing import (
TraceConfig as TraceConfig,
TraceConnectionCreateEndParams as TraceConnectionCreateEndParams,
TraceConnectionCreateStartParams as TraceConnectionCreateStartParams,
TraceConnectionQueuedEndParams as TraceConnectionQueuedEndParams,
TraceConnectionQueuedStartParams as TraceConnectionQueuedStartParams,
TraceConnectionReuseconnParams as TraceConnectionReuseconnParams,
TraceDnsCacheHitParams as TraceDnsCacheHitParams,
TraceDnsCacheMissParams as TraceDnsCacheMissParams,
TraceDnsResolveHostEndParams as TraceDnsResolveHostEndParams,
TraceDnsResolveHostStartParams as TraceDnsResolveHostStartParams,
TraceRequestChunkSentParams as TraceRequestChunkSentParams,
TraceRequestEndParams as TraceRequestEndParams,
TraceRequestExceptionParams as TraceRequestExceptionParams,
TraceRequestHeadersSentParams as TraceRequestHeadersSentParams,
TraceRequestRedirectParams as TraceRequestRedirectParams,
TraceRequestStartParams as TraceRequestStartParams,
TraceResponseChunkReceivedParams as TraceResponseChunkReceivedParams,
)
if TYPE_CHECKING:
# At runtime these are lazy-loaded at the bottom of the file.
from .worker import (
GunicornUVLoopWebWorker as GunicornUVLoopWebWorker,
GunicornWebWorker as GunicornWebWorker,
)
__all__: tuple[str, ...] = (
"hdrs",
# client
"AddrInfoType",
"BaseConnector",
"ClientConnectionError",
"ClientConnectionResetError",
"ClientConnectorCertificateError",
"ClientConnectorDNSError",
"ClientConnectorError",
"ClientConnectorSSLError",
"ClientError",
"ClientHttpProxyError",
"ClientOSError",
"ClientPayloadError",
"ClientProxyConnectionError",
"ClientResponse",
"ClientRequest",
"ClientResponseError",
"ClientSSLError",
"ClientSession",
"ClientTimeout",
"ClientWebSocketResponse",
"ClientWSTimeout",
"ConnectionTimeoutError",
"ContentTypeError",
"Fingerprint",
"FlowControlDataQueue",
"InvalidURL",
"InvalidUrlClientError",
"InvalidUrlRedirectClientError",
"NonHttpUrlClientError",
"NonHttpUrlRedirectClientError",
"RedirectClientError",
"RequestInfo",
"ServerConnectionError",
"ServerDisconnectedError",
"ServerFingerprintMismatch",
"ServerTimeoutError",
"SocketFactoryType",
"SocketTimeoutError",
"TCPConnector",
"TooManyRedirects",
"UnixConnector",
"NamedPipeConnector",
"WSServerHandshakeError",
"request",
# client_middleware
"ClientMiddlewareType",
"ClientHandlerType",
# cookiejar
"CookieJar",
"DummyCookieJar",
# formdata
"FormData",
# helpers
"BasicAuth",
"ChainMapProxy",
"DigestAuthMiddleware",
"ETag",
"encode_basic_auth",
"set_zlib_backend",
# http
"HttpVersion",
"HttpVersion10",
"HttpVersion11",
"WSMsgType",
"WSCloseCode",
"WSMessage",
"WebSocketError",
# multipart
"BadContentDispositionHeader",
"BadContentDispositionParam",
"BodyPartReader",
"MultipartReader",
"MultipartWriter",
"content_disposition_filename",
"parse_content_disposition",
# payload
"AsyncIterablePayload",
"BufferedReaderPayload",
"BytesIOPayload",
"BytesPayload",
"IOBasePayload",
"JsonPayload",
"PAYLOAD_REGISTRY",
"Payload",
"StringIOPayload",
"StringPayload",
"TextIOPayload",
"get_payload",
"payload_type",
# payload_streamer
"streamer",
# resolver
"AsyncResolver",
"DefaultResolver",
"ThreadedResolver",
# streams
"DataQueue",
"EMPTY_PAYLOAD",
"EofStream",
"StreamReader",
# tracing
"TraceConfig",
"TraceConnectionCreateEndParams",
"TraceConnectionCreateStartParams",
"TraceConnectionQueuedEndParams",
"TraceConnectionQueuedStartParams",
"TraceConnectionReuseconnParams",
"TraceDnsCacheHitParams",
"TraceDnsCacheMissParams",
"TraceDnsResolveHostEndParams",
"TraceDnsResolveHostStartParams",
"TraceRequestChunkSentParams",
"TraceRequestEndParams",
"TraceRequestExceptionParams",
"TraceRequestHeadersSentParams",
"TraceRequestRedirectParams",
"TraceRequestStartParams",
"TraceResponseChunkReceivedParams",
# workers (imported lazily with __getattr__)
"GunicornUVLoopWebWorker",
"GunicornWebWorker",
"WSMessageTypeError",
)
def __dir__() -> tuple[str, ...]:
return __all__ + ("__doc__",)
def __getattr__(name: str) -> object:
global GunicornUVLoopWebWorker, GunicornWebWorker
# Importing gunicorn takes a long time (>100ms), so only import if actually needed.
if name in ("GunicornUVLoopWebWorker", "GunicornWebWorker"):
try:
from .worker import GunicornUVLoopWebWorker as guv, GunicornWebWorker as gw
except ImportError:
return None
GunicornUVLoopWebWorker = guv # type: ignore[misc]
GunicornWebWorker = gw # type: ignore[misc]
return guv if name == "GunicornUVLoopWebWorker" else gw
raise AttributeError(f"module {__name__} has no attribute {name}")

Some files were not shown because too many files have changed in this diff Show More