repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
aiohttp
tests/test_benchmarks_web_request.py
.py
"""codspeed benchmarks for web request reading.""" import asyncio import zlib from typing import TYPE_CHECKING import pytest from pytest_aiohttp import AiohttpClient from aiohttp import web if TYPE_CHECKING: from pytest_codspeed import BenchmarkFixture else: pytest_codspeed = pytest.importorskip("pytest_cod...
49
1,388
aiohttp
tests/test_flowcontrol_streams.py
.py
import asyncio from unittest import mock import pytest from aiohttp import streams from aiohttp.base_protocol import BaseProtocol from aiohttp.http_parser import HttpParser @pytest.fixture def protocol() -> BaseProtocol: return mock.create_autospec(BaseProtocol, spec_set=True, instance=True, _reading_paused=Fal...
131
5,147
aiohttp
tests/test_web_log.py
.py
import datetime import logging import platform import sys from contextvars import ContextVar from typing import NoReturn from unittest import mock import pytest from pytest_aiohttp import AiohttpClient, AiohttpRawServer, AiohttpServer import aiohttp from aiohttp import web from aiohttp.abc import AbstractAccessLogger...
481
16,889
aiohttp
tests/test_web_urldispatcher.py
.py
import asyncio import functools import os import pathlib import socket import sys from collections.abc import Generator from stat import S_IFIFO, S_IMODE from typing import Any, NoReturn import pytest import yarl from pytest_aiohttp import AiohttpClient from aiohttp import web from aiohttp.web_urldispatcher import Re...
1,018
32,667
aiohttp
tests/test_websocket_parser.py
.py
import asyncio import pickle import random import struct import zlib from unittest import mock import pytest from aiohttp._websocket import helpers as _websocket_helpers from aiohttp._websocket.helpers import ( PACK_CLOSE_CODE, PACK_LEN1, PACK_LEN2, PACK_LEN3, PACK_RANDBITS, websocket_mask, ) ...
936
33,270
aiohttp
tests/test_client_fingerprint.py
.py
import hashlib from unittest import mock import pytest import aiohttp ssl = pytest.importorskip("ssl") def test_fingerprint_sha256() -> None: sha256 = hashlib.sha256(b"12345678" * 64).digest() fp = aiohttp.Fingerprint(sha256) assert fp.fingerprint == sha256 def test_fingerprint_sha1() -> None: sh...
35
831
aiohttp
tests/test_benchmarks_http_websocket.py
.py
"""codspeed benchmarks for http websocket.""" import asyncio from typing import TYPE_CHECKING import pytest from aiohttp._websocket.helpers import MSG_SIZE, PACK_LEN3 from aiohttp._websocket.reader import WebSocketDataQueue from aiohttp.base_protocol import BaseProtocol from aiohttp.helpers import DEFAULT_CHUNK_SIZE...
154
5,262
aiohttp
tests/test_multipart.py
.py
import asyncio import gzip import io import json import pathlib import sys from collections.abc import AsyncIterator from types import TracebackType from unittest import mock import pytest from multidict import CIMultiDict import aiohttp from aiohttp import payload from aiohttp.abc import AbstractStreamWriter from ai...
1,895
69,567
aiohttp
tests/test_connector.py
.py
# Tests of http client with custom Connector import asyncio import contextlib import gc import hashlib import platform import socket import ssl import sys import uuid import warnings from collections import defaultdict, deque from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Sequence from concur...
4,864
158,708
aiohttp
tests/test_cookiejar.py
.py
import datetime import heapq import itertools import json import logging import os import stat from http.cookies import BaseCookie, Morsel, SimpleCookie from operator import not_ from pathlib import Path from types import MappingProxyType from unittest import mock import pytest from freezegun import freeze_time from y...
1,859
62,229
aiohttp
tests/test_web_sendfile.py
.py
import asyncio import io from pathlib import Path from stat import S_IFREG, S_IRUSR, S_IWUSR from unittest import mock from aiohttp import hdrs from aiohttp.http_writer import StreamWriter from aiohttp.test_utils import make_mocked_request from aiohttp.web_fileresponse import FileResponse MOCK_MODE = S_IFREG | S_IRUS...
200
7,309
aiohttp
tests/test_route_def.py
.py
import pathlib from typing import NoReturn import pytest from yarl import URL from aiohttp import web from aiohttp.web_urldispatcher import UrlDispatcher @pytest.fixture def router() -> UrlDispatcher: return UrlDispatcher() def test_get(router: UrlDispatcher) -> None: async def handler(request: web.Reques...
322
8,167
aiohttp
tests/test_client_ws.py
.py
import asyncio import base64 import hashlib import os from collections.abc import Mapping from unittest import mock import pytest import aiohttp from aiohttp import ( ClientConnectionResetError, ClientWSTimeout, ServerDisconnectedError, client, hdrs, ) from aiohttp._websocket.writer import WebSock...
1,008
36,097
aiohttp
tests/test_client_ws_functional.py
.py
import asyncio import json import struct import sys import zlib from typing import Literal, NoReturn from unittest import mock import pytest from pytest_aiohttp import AiohttpClient, AiohttpServer import aiohttp from aiohttp import ( ClientConnectionResetError, ServerTimeoutError, WSMessageTypeError, ...
1,681
52,680
aiohttp
tests/test_benchmarks_web_middleware.py
.py
"""codspeed benchmarks for web middlewares.""" import asyncio from typing import TYPE_CHECKING import pytest from pytest_aiohttp import AiohttpClient from aiohttp import web from aiohttp.typedefs import Handler if TYPE_CHECKING: from pytest_codspeed import BenchmarkFixture else: pytest_codspeed = pytest.imp...
51
1,362
aiohttp
tests/test_resolver.py
.py
import asyncio import gc import ipaddress import socket from collections.abc import Awaitable, Callable, Collection, Generator from ipaddress import ip_address from typing import Any, NamedTuple from unittest.mock import AsyncMock, Mock, call, create_autospec, patch import pytest from aiohttp.resolver import ( _N...
762
26,379
aiohttp
tests/test_urldispatch.py
.py
import pathlib import platform import re from collections.abc import ( Awaitable, Callable, Container, Iterable, Mapping, MutableMapping, Sized, ) from functools import partial from typing import NoReturn from urllib.parse import quote, unquote import pytest from yarl import URL import aio...
1,437
48,822
aiohttp
tests/test_client_exceptions.py
.py
import errno import pickle import sys import pytest from multidict import CIMultiDict, CIMultiDictProxy from yarl import URL from aiohttp import client, client_reqrep from aiohttp.helpers import HeadersDictProxy from aiohttp.http_parser import RawResponseMessage from aiohttp.typedefs import StrOrURL if sys.version_i...
337
12,576
aiohttp
tests/test_benchmarks_cookie_helpers.py
.py
"""codspeed benchmarks for cookie helpers.""" from typing import TYPE_CHECKING import pytest from aiohttp._cookie_helpers import _COOKIE_PATTERN if TYPE_CHECKING: from pytest_codspeed import BenchmarkFixture else: pytest_codspeed = pytest.importorskip("pytest_codspeed") BenchmarkFixture = pytest_codspee...
29
842
aiohttp
tests/test_tracing.py
.py
import sys from types import SimpleNamespace from typing import Any from unittest import mock from unittest.mock import Mock import pytest from aiosignal import Signal from aiohttp import ClientSession from aiohttp.tracing import ( Trace, TraceConfig, TraceConnectionCreateEndParams, TraceConnectionCre...
156
5,868
aiohttp
tests/test_web_app.py
.py
import asyncio import logging import sys from collections.abc import AsyncIterator, Callable, Iterator from contextlib import asynccontextmanager from typing import NoReturn from unittest import mock import pytest from pytest_aiohttp import AiohttpClient, AiohttpServer from aiohttp import hdrs, log, web from aiohttp....
811
23,177
aiohttp
tests/test_web_websocket.py
.py
import asyncio import json import time from typing import Protocol from unittest import mock import aiosignal import pytest from multidict import CIMultiDict from pytest_mock import MockerFixture from aiohttp import WSMessageTypeError, WSMsgType, web from aiohttp.http import WS_CLOSED_MESSAGE, WS_CLOSING_MESSAGE from...
760
23,000
aiohttp
tests/test_payload.py
.py
import array import asyncio import io import json import unittest.mock from collections.abc import AsyncIterator, Iterator from io import StringIO from pathlib import Path from typing import TextIO, Union import pytest from multidict import CIMultiDict from aiohttp import payload from aiohttp.abc import AbstractStrea...
1,445
50,152
aiohttp
tests/test_streams.py
.py
# Tests for streams.py import abc import asyncio import gc import types from collections import defaultdict from collections.abc import Callable, Coroutine, Iterator, Sequence from itertools import groupby from typing import TypeVar from unittest import mock import pytest from aiohttp import streams from aiohttp.bas...
1,958
61,921
aiohttp
tests/test_web_websocket_functional.py
.py
# HTTP websocket server functional tests import asyncio import contextlib import json import sys import weakref from typing import Literal, NoReturn from unittest import mock import pytest from pytest_aiohttp import AiohttpClient, AiohttpServer import aiohttp from aiohttp import WSServerHandshakeError, hdrs, web fro...
1,776
54,389
aiohttp
tests/test_benchmarks_client_ws.py
.py
"""codspeed benchmarks for websocket client.""" import asyncio import ssl from collections.abc import Awaitable, Callable, Iterator from dataclasses import dataclass from typing import TYPE_CHECKING, Any, TypedDict import pytest from pytest_aiohttp import AiohttpClient from aiohttp import web from aiohttp._websocket...
240
7,437
aiohttp
tests/test_client_middleware.py
.py
"""Tests for client middleware.""" import json import socket from typing import NoReturn import pytest from pytest_aiohttp import AiohttpServer from aiohttp import ( ClientError, ClientHandlerType, ClientRequest, ClientResponse, ClientSession, ClientTimeout, TCPConnector, web, ) from ...
1,340
47,947
aiohttp
tests/test_web_exceptions.py
.py
import collections import pickle from collections.abc import Mapping from traceback import format_exception from typing import NoReturn import pytest from pytest_aiohttp import AiohttpClient from yarl import URL from aiohttp import web def test_all_http_exceptions_exported() -> None: assert "HTTPException" in w...
421
14,430
aiohttp
tests/test_client_connection.py
.py
import asyncio import gc from typing import Any from unittest import mock import pytest from aiohttp.client_proto import ResponseHandler from aiohttp.client_reqrep import ConnectionKey from aiohttp.connector import BaseConnector, Connection @pytest.fixture def key() -> object: return object() @pytest.fixture ...
187
4,818
aiohttp
tests/test_client_proto.py
.py
import asyncio from unittest import mock import pytest from multidict import CIMultiDict from pytest_mock import MockerFixture from yarl import URL from aiohttp import http from aiohttp.abc import AbstractStreamWriter from aiohttp.client_exceptions import ClientOSError, ServerDisconnectedError from aiohttp.client_pro...
430
14,108
aiohttp
tests/test_web_protocol.py
.py
import asyncio from unittest import mock import pytest from aiohttp.http import WebSocketReader from aiohttp.web_protocol import RequestHandler from aiohttp.web_request import BaseRequest from aiohttp.web_server import Server @pytest.fixture def dummy_manager() -> Server[BaseRequest]: return mock.create_autospe...
145
4,773
aiohttp
tests/test_worker.py
.py
# Tests for aiohttp/worker.py import asyncio import os import socket import ssl from typing import TYPE_CHECKING from unittest import mock import pytest from _pytest.fixtures import SubRequest from aiohttp import web if TYPE_CHECKING: from aiohttp import worker as base_worker else: base_worker = pytest.impor...
316
9,255
aiohttp
tests/test_benchmarks_cookiejar.py
.py
"""codspeed benchmarks for cookies.""" from http.cookies import BaseCookie from typing import TYPE_CHECKING import pytest from yarl import URL from aiohttp.cookiejar import CookieJar if TYPE_CHECKING: from pytest_codspeed import BenchmarkFixture else: pytest_codspeed = pytest.importorskip("pytest_codspeed")...
34
1,003
aiohttp
tests/test_http_writer.py
.py
# Tests for aiohttp/http_writer.py import array import asyncio import zlib from collections.abc import Generator, Iterable from typing import Any from unittest import mock import pytest from multidict import CIMultiDict from aiohttp import ClientConnectionResetError, hdrs, http from aiohttp.base_protocol import BaseP...
1,598
57,701
aiohttp
tests/test_benchmarks_web_urldispatcher.py
.py
"""codspeed benchmarks for the URL dispatcher.""" import asyncio import json import pathlib import random import string from pathlib import Path from typing import TYPE_CHECKING, NoReturn, cast from unittest import mock import pytest from multidict import CIMultiDict from yarl import URL import aiohttp from aiohttp ...
582
18,051
aiohttp
tests/test_http_exceptions.py
.py
# Tests for http_exceptions.py import pickle import sys from multidict import CIMultiDict from aiohttp import http_exceptions if sys.version_info >= (3, 11): from typing import assert_type class TestHttpProcessingError: def test_ctor(self) -> None: err = http_exceptions.HttpProcessingError( ...
166
6,114
aiohttp
tests/test_client_response.py
.py
# Tests for aiohttp/client.py import asyncio import gc import sys from http.cookies import SimpleCookie from json import JSONDecodeError from unittest import mock import pytest from multidict import CIMultiDict from pytest_mock import MockerFixture from yarl import URL import aiohttp from aiohttp import ClientSessio...
1,793
54,175
aiohttp
tests/test_client_middleware_digest_auth.py
.py
"""Test digest authentication middleware for aiohttp client.""" import io import re import time from collections.abc import Generator from hashlib import md5, sha1 from typing import Literal from unittest import mock import pytest from pytest_aiohttp import AiohttpServer from yarl import URL from aiohttp import Clie...
1,691
60,248
aiohttp
tests/test_run_app.py
.py
import asyncio import contextlib import logging import os import platform import signal import socket import ssl import subprocess import sys import time import traceback from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Iterator from typing import Any, NoReturn from unittest import mock from u...
1,567
47,573
aiohttp
tests/test_web_sendfile_functional.py
.py
import asyncio import bz2 import contextlib import gzip import pathlib import socket from collections.abc import AsyncIterator, Iterable from typing import Protocol from unittest import mock import pytest from _pytest.fixtures import SubRequest from pytest_aiohttp import AiohttpClient, AiohttpServer import aiohttp fr...
1,248
38,155
aiohttp
tests/test_benchmarks_client.py
.py
"""codspeed benchmarks for HTTP client.""" import asyncio import ssl from collections.abc import Awaitable, Callable, Iterator from dataclasses import dataclass from typing import TYPE_CHECKING, Any, TypedDict import pytest from pytest_aiohttp import AiohttpClient, AiohttpServer from yarl import URL from aiohttp imp...
654
19,750
aiohttp
tests/test_websocket_handshake.py
.py
# Tests for http/websocket.py import base64 import os import pytest from aiohttp import web from aiohttp.test_utils import make_mocked_request def gen_ws_headers( protocols: str = "", compress: int = 0, extension_text: str = "", server_notakeover: bool = False, client_notakeover: bool = False, ...
297
8,385
aiohttp
tests/test_http_parser.py
.py
# Tests for aiohttp/protocol.py import asyncio import gzip import platform import re import sys import zlib from collections.abc import Iterable, Iterator from contextlib import suppress from typing import Any from unittest import mock from urllib.parse import quote import pytest from multidict import CIMultiDict fro...
3,617
127,335
aiohttp
tests/test_multipart_helpers.py
.py
import pytest import aiohttp from aiohttp import content_disposition_filename, parse_content_disposition class TestParseContentDisposition: # http://greenbytes.de/tech/tc2231/ def test_parse_empty(self) -> None: disptype, params = parse_content_disposition(None) assert disptype is None ...
808
32,105
aiohttp
tests/test_helpers.py
.py
import asyncio import datetime import gc import ipaddress import itertools import sys import time import weakref from collections.abc import Iterator from math import ceil, modf from pathlib import Path from types import MappingProxyType from unittest import mock from urllib.request import getproxies_environment impor...
1,225
38,172
aiohttp
tests/test_web_cli.py
.py
import sys from unittest import mock import pytest from pytest_mock import MockerFixture from aiohttp import web def test_entry_func_empty(mocker: MockerFixture) -> None: error = mocker.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit) argv = [""] with pytest.raises(SystemExit): ...
162
5,259
aiohttp
tests/test_web_server.py
.py
import asyncio import gc import socket from contextlib import suppress from typing import Any, NoReturn from unittest import mock import pytest from pytest_aiohttp import AiohttpClient, AiohttpRawServer, AiohttpServer from aiohttp import client, web from aiohttp.http_exceptions import BadStatusLine async def test_s...
422
14,142
aiohttp
tests/test_web_response.py
.py
import asyncio import collections.abc import datetime import gzip import io import json import re import sys import weakref from collections.abc import AsyncIterator, Iterator from concurrent.futures import ThreadPoolExecutor from unittest import mock import aiosignal import pytest from multidict import CIMultiDict, C...
1,680
52,434
aiohttp
tests/conftest.py
.py
from __future__ import annotations # TODO(PY311): Remove import asyncio import base64 import os import platform import socket import ssl import sys import time from collections.abc import AsyncIterator, Callable, Iterator from concurrent.futures import Future, ThreadPoolExecutor from hashlib import md5, sha1, sha256 ...
517
16,753
aiohttp
tests/isolated/check_for_request_leak.py
.py
import asyncio import gc import socket import sys from typing import NoReturn from aiohttp import ClientSession, web from aiohttp.test_utils import REUSE_ADDRESS gc.set_debug(gc.DEBUG_LEAK) async def main() -> None: app = web.Application() async def handler(request: web.Request) -> NoReturn: await ...
43
1,145
aiohttp
tests/isolated/check_for_client_response_leak.py
.py
import asyncio import contextlib import gc import socket import sys from aiohttp import ClientError, ClientSession, web from aiohttp.test_utils import REUSE_ADDRESS gc.set_debug(gc.DEBUG_LEAK) async def main() -> None: app = web.Application() async def stream_handler(request: web.Request) -> web.Response: ...
51
1,423
aiohttp
tests/autobahn/test_autobahn.py
.py
import json import os import pprint import socket import subprocess import sys import time from collections.abc import Iterator from pathlib import Path from typing import TYPE_CHECKING import pytest from pytest import TempPathFactory if TYPE_CHECKING: from python_on_whales import docker else: python_on_whale...
224
7,888
aiohttp
tests/autobahn/client/client.py
.py
#!/usr/bin/env python3 import asyncio from aiohttp import ClientSession, WSMsgType async def client(url: str, name: str) -> None: async with ClientSession(base_url=url) as session: async with session.ws_connect("/getCaseCount") as ws: msg = await ws.receive() assert msg.type is W...
33
1,061
aiohttp
tests/autobahn/server/server.py
.py
#!/usr/bin/env python3 import logging from aiohttp import WSCloseCode, web websockets = web.AppKey("websockets", list[web.WebSocketResponse]) async def wshandler(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse(autoclose=False) await ws.prepare(request) request.app[websockets...
42
1,075
aiohttp
examples/cli_app.py
.py
#!/usr/bin/env python3 """ Example of serving an Application using the `aiohttp.web` CLI. Serve this app using:: $ python -m aiohttp.web -H localhost -P 8080 --repeat 10 cli_app:init \ > "Hello World" Here ``--repeat`` & ``"Hello World"`` are application specific command-line arguments. `aiohttp.web` only pa...
55
1,573
aiohttp
examples/combined_middleware.py
.py
#!/usr/bin/env python3 """ Example of combining multiple middleware with aiohttp client. This example shows how to chain multiple middleware together to create a powerful request pipeline. Middleware are applied in order, demonstrating how logging, authentication, and retry logic can work together. The order of middl...
321
10,619
aiohttp
examples/curl.py
.py
#!/usr/bin/env python3 import argparse import asyncio import sys import aiohttp async def curl(url: str) -> None: async with aiohttp.ClientSession() as session: async with session.request("GET", url) as response: print(repr(response)) chunk = await response.content.read() ...
38
1,069
aiohttp
examples/client_ws.py
.py
#!/usr/bin/env python3 """websocket cmd client for web_ws.py example.""" import argparse import asyncio import sys from contextlib import suppress import aiohttp async def start_client(url: str) -> None: name = input("Please enter your name: ") async def dispatch(ws: aiohttp.ClientWebSocketResponse) -> Non...
70
2,161
aiohttp
examples/fake_server.py
.py
#!/usr/bin/env python3 import asyncio import pathlib import socket import ssl from aiohttp import ClientSession, TCPConnector, web from aiohttp.abc import AbstractResolver, ResolveResult from aiohttp.resolver import DefaultResolver class FakeResolver(AbstractResolver): _LOCAL_HOST = {0: "127.0.0.1", socket.AF_IN...
121
3,890
aiohttp
examples/token_refresh_middleware.py
.py
#!/usr/bin/env python3 """ Example of using token refresh middleware with aiohttp client. This example shows how to implement a middleware that handles JWT token refresh automatically. The middleware: - Adds bearer tokens to requests - Detects when tokens are expired - Automatically refreshes tokens when needed - Hand...
338
12,264
aiohttp
examples/web_ws.py
.py
#!/usr/bin/env python3 """Example for aiohttp.web websocket server.""" # The extra strict mypy settings are here to help test that `Application[AppKey()]` # syntax is working correctly. A regression will cause mypy to raise an error. # mypy: disallow-any-expr, disallow-any-unimported, disallow-subclassing-any import ...
64
1,841
aiohttp
examples/client_auth.py
.py
#!/usr/bin/env python3 import asyncio import aiohttp async def fetch(session: aiohttp.ClientSession) -> None: print("Query http://httpbin.org/basic-auth/andrew/password") async with session.get("http://httpbin.org/basic-auth/andrew/password") as resp: print(resp.status) body = await resp.text...
23
609
aiohttp
examples/web_srv.py
.py
#!/usr/bin/env python3 """Example for aiohttp.web basic server.""" import textwrap from aiohttp import web async def intro(request: web.Request) -> web.StreamResponse: txt = textwrap.dedent("""\ Type {url}/hello/John {url}/simple or {url}/change_body in browser url bar """).format(url="127....
57
1,529
aiohttp
examples/background_tasks.py
.py
#!/usr/bin/env python3 """Example of aiohttp.web.Application.on_startup signal handler""" import asyncio from collections.abc import AsyncIterator from contextlib import asynccontextmanager, suppress import valkey.asyncio as valkey from aiohttp import web valkey_listener = web.AppKey("valkey_listener", asyncio.Task...
71
2,048
aiohttp
examples/web_classview.py
.py
#!/usr/bin/env python3 """Example for aiohttp.web class based views.""" import functools import json from aiohttp import web class MyView(web.View): async def get(self) -> web.StreamResponse: return web.json_response( { "method": self.request.method, "args": d...
61
1,587
aiohttp
examples/web_srv_route_table.py
.py
#!/usr/bin/env python3 """Example for aiohttp.web basic server with table definition for routes.""" import textwrap from aiohttp import web async def intro(request: web.Request) -> web.StreamResponse: txt = textwrap.dedent("""\ Type {url}/hello/John {url}/simple or {url}/change_body in browser ...
61
1,605
aiohttp
examples/server_simple.py
.py
# server_simple.py from aiohttp import web async def handle(request: web.Request) -> web.StreamResponse: name = request.match_info.get("name", "Anonymous") text = "Hello, " + name return web.Response(text=text) async def wshandle(request: web.Request) -> web.StreamResponse: ws = web.WebSocketRespons...
32
788
aiohttp
examples/web_rewrite_headers_middleware.py
.py
#!/usr/bin/env python3 """Example for rewriting response headers by middleware.""" from aiohttp import web from aiohttp.typedefs import Handler async def handler(request: web.Request) -> web.StreamResponse: return web.Response(text="Everything is fine") async def middleware(request: web.Request, handler: Handl...
29
725
aiohttp
examples/web_cookies.py
.py
#!/usr/bin/env python3 """Example for aiohttp.web basic server with cookies.""" from pprint import pformat from typing import NoReturn from aiohttp import web tmpl = """\ <html> <body> <a href="/login">Login</a><br/> <a href="/logout">Logout</a><br/> <pre>{}</pre> </body> </html>""" ...
46
990
aiohttp
examples/digest_auth_qop_auth.py
.py
#!/usr/bin/env python3 """ Example of using digest authentication middleware with aiohttp client. This example shows how to use the DigestAuthMiddleware from aiohttp.client_middleware_digest_auth to authenticate with a server that requires digest authentication with different qop options. In this case, it connects to...
69
2,273
aiohttp
examples/lowlevel_srv.py
.py
import asyncio from aiohttp import web, web_request async def handler(request: web_request.BaseRequest) -> web.StreamResponse: return web.Response(text="OK") async def main(loop: asyncio.AbstractEventLoop) -> None: server = web.Server(handler) await loop.create_server(server, "127.0.0.1", 8080) pri...
27
645
aiohttp
examples/retry_middleware.py
.py
#!/usr/bin/env python3 """ Example of using retry middleware with aiohttp client. This example shows how to implement a middleware that automatically retries failed requests with exponential backoff. The middleware can be configured with custom retry statuses, maximum retries, and backoff parameters. This example inc...
246
8,863
aiohttp
examples/web_srv_route_deco.py
.py
#!/usr/bin/env python3 """Example for aiohttp.web basic server with decorator definition for routes.""" import textwrap from aiohttp import web routes = web.RouteTableDef() @routes.get("/") async def intro(request: web.Request) -> web.StreamResponse: txt = textwrap.dedent("""\ Type {url}/hello/John {u...
59
1,504
aiohttp
examples/static_files.py
.py
#!/usr/bin/env python3 import pathlib from aiohttp import web app = web.Application() app.router.add_static("/", pathlib.Path(__file__).parent, show_index=True) web.run_app(app)
10
181
aiohttp
examples/client_json.py
.py
#!/usr/bin/env python3 import asyncio import aiohttp async def fetch(session: aiohttp.ClientSession) -> None: print("Query http://httpbin.org/get") async with session.get("http://httpbin.org/get") as resp: print(resp.status) data = await resp.json() print(data) async def go() -> Non...
23
480
aiohttp
examples/logging_middleware.py
.py
#!/usr/bin/env python3 """ Example of using logging middleware with aiohttp client. This example shows how to implement a middleware that logs request timing and response status. This is useful for debugging, monitoring, and understanding the flow of HTTP requests in your application. This example includes a test ser...
171
5,728
aiohttp
examples/basic_auth_middleware.py
.py
#!/usr/bin/env python3 """ Example of using basic authentication middleware with aiohttp client. This example shows how to implement a middleware that automatically adds Basic Authentication headers to all requests. The middleware encodes the username and password in base64 format as required by the HTTP Basic Auth sp...
191
6,441
sanic
setup.py
.py
""" Sanic """ import codecs import os import re import sys from setuptools import find_packages, setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): """ Provide a Test runner to be used from setup.py to run unit tests """ user_options = [("pytest-args=", "a", "A...
198
4,647
sanic
sanic/middleware.py
.py
from __future__ import annotations from collections import deque from collections.abc import Sequence from enum import IntEnum, auto from itertools import count from sanic.models.handler_types import MiddlewareType class MiddlewareLocation(IntEnum): REQUEST = auto() RESPONSE = auto() class Middleware: ...
106
2,989
sanic
sanic/simple.py
.py
from pathlib import Path from sanic import Sanic from sanic.exceptions import SanicException def create_simple_server(directory: Path): if not directory.is_dir(): raise SanicException( "Cannot setup Sanic Simple Server without a path to a directory" ) app = Sanic("SimpleServer") ...
19
435
sanic
sanic/app.py
.py
from __future__ import annotations import asyncio import logging import logging.config import re import sys from asyncio import ( AbstractEventLoop, CancelledError, Task, ensure_future, get_running_loop, wait_for, ) from asyncio.futures import Future from collections import defaultdict, deque ...
2,553
92,936
sanic
sanic/utils.py
.py
import types from importlib.util import module_from_spec, spec_from_file_location from os import environ as os_environ from pathlib import Path from re import findall as re_findall from sanic.exceptions import LoadFileException, PyFileError from sanic.helpers import import_string def str_to_bool(val: str) -> bool: ...
141
4,484
sanic
sanic/exceptions.py
.py
from asyncio import CancelledError from collections.abc import Sequence from os import PathLike from typing import Any from sanic.helpers import STATUS_CODES from sanic.models.protocol_types import Range class RequestCancelled(CancelledError): quiet = True class ServerKilled(Exception): """Exception Sanic ...
679
27,513
sanic
sanic/headers.py
.py
from __future__ import annotations import re from collections.abc import Iterable from typing import Any from urllib.parse import unquote from sanic.exceptions import InvalidHeader from sanic.helpers import STATUS_CODES # TODO: # - the Options object should be a typed object to allow for less casting # across th...
551
18,775
sanic
sanic/__main__.py
.py
import tracerite try: tracerite.load() except Exception as exc: raise RuntimeError( "Failed to initialize tracerite. Please verify that tracerite is " "correctly installed and compatible with this environment." ) from exc from sanic.cli.app import SanicCLI from sanic.compat import OS_IS_WI...
30
675
sanic
sanic/__init__.py
.py
from types import SimpleNamespace from typing_extensions import TypeAlias from sanic.__version__ import __version__ from sanic.app import Sanic from sanic.blueprints import Blueprint from sanic.config import Config from sanic.constants import HTTPMethod from sanic.exceptions import ( BadRequest, ExpectationFa...
87
1,752
sanic
sanic/constants.py
.py
from enum import auto from sanic.compat import UpperStrEnum class HTTPMethod(UpperStrEnum): """HTTP methods that are commonly used.""" GET = auto() POST = auto() PUT = auto() HEAD = auto() OPTIONS = auto() PATCH = auto() DELETE = auto() class LocalCertCreator(UpperStrEnum): """...
39
862
sanic
sanic/router.py
.py
from __future__ import annotations from collections.abc import Iterable from functools import lru_cache from inspect import signature from typing import Any from uuid import UUID from sanic_routing import BaseRouter from sanic_routing.exceptions import NoMethod from sanic_routing.exceptions import NotFound as Routing...
274
9,283
sanic
sanic/asgi.py
.py
from __future__ import annotations import warnings from typing import TYPE_CHECKING from sanic.compat import Header from sanic.exceptions import BadRequest, ServerError from sanic.helpers import Default from sanic.http import Stage from sanic.log import error_logger, logger from sanic.models.asgi import ASGIReceive,...
264
9,383
sanic
sanic/views.py
.py
from __future__ import annotations from collections.abc import Iterable from typing import ( TYPE_CHECKING, Any, Callable, ) from sanic.models.handler_types import RouteHandler from sanic.request.types import Request if TYPE_CHECKING: from sanic import Sanic from sanic.blueprints import Blueprin...
246
8,507
sanic
sanic/signals.py
.py
from __future__ import annotations import asyncio from collections import deque from dataclasses import dataclass from enum import Enum from inspect import isawaitable from typing import Any, cast from sanic_routing import BaseRouter, Route, RouteGroup from sanic_routing.exceptions import NotFound from sanic_routing...
421
14,735
sanic
sanic/log.py
.py
from sanic.logging.color import Colors from sanic.logging.default import LOGGING_CONFIG_DEFAULTS from sanic.logging.deprecation import deprecation from sanic.logging.filter import VerbosityFilter from sanic.logging.loggers import ( access_logger, error_logger, logger, server_logger, websockets_logge...
25
529
sanic
sanic/compat.py
.py
import asyncio import os import platform import signal import sys from collections.abc import Awaitable from contextlib import contextmanager from enum import Enum from typing import Literal from multidict import CIMultiDict # type: ignore from sanic.helpers import Default from sanic.log import error_logger Start...
197
5,907
sanic
sanic/blueprints.py
.py
from __future__ import annotations import asyncio from collections import defaultdict from collections.abc import Iterable, Iterator, MutableSequence, Sequence from copy import deepcopy from functools import partial, wraps from inspect import isfunction from itertools import chain from types import SimpleNamespace fr...
984
32,509
sanic
sanic/helpers.py
.py
"""Defines basics of HTTP standard.""" import sys from functools import partial from importlib import import_module from inspect import ismodule try: from ujson import dumps as ujson_dumps json_dumps = partial(ujson_dumps, escape_forward_slashes=False) except ImportError: # This is done in order to ens...
174
4,593
sanic
sanic/config.py
.py
from __future__ import annotations from abc import ABC, ABCMeta, abstractmethod from collections.abc import Sequence from inspect import getmembers, isclass, isdatadescriptor from os import environ from pathlib import Path from typing import Any, Callable, Literal from warnings import filterwarnings from sanic.consta...
496
16,111
sanic
sanic/errorpages.py
.py
""" Sanic `provides a pattern <https://sanicframework.org/guide/best-practices/exceptions.html#using-sanic-exceptions>`_ for providing a response when an exception occurs. However, if you do no handle an exception, it will provide a fallback. There are three fallback types: - HTML - *default* - Text - JSON Setting ``...
406
12,859
sanic
sanic/blueprint_group.py
.py
from .blueprints import BlueprintGroup __all__ = ["BlueprintGroup"] # noqa: F405
5
84
sanic
sanic/application/spinner.py
.py
import os import sys import time from contextlib import contextmanager from queue import Queue from threading import Thread if os.name == "nt": # noqa import ctypes # noqa class _CursorInfo(ctypes.Structure): _fields_ = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] class Spinner: # noqa ...
91
2,347
sanic
sanic/application/state.py
.py
from __future__ import annotations import logging from dataclasses import dataclass, field from pathlib import Path from socket import socket from ssl import SSLContext from typing import TYPE_CHECKING, Any from sanic.application.constants import Mode, Server, ServerStage from sanic.log import VerbosityFilter, logge...
116
3,575