text
stringlengths
1
843k
from contextlib import asynccontextmanager as asynccontextmanager from typing import AsyncGenerator, ContextManager, TypeVar import anyio.to_thread from anyio import CapacityLimiter from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa from starlette.concurrency import run_in_threadp...
from typing import ( Any, BinaryIO, Callable, Dict, Iterable, Optional, Type, TypeVar, cast, ) from fastapi._compat import ( PYDANTIC_V2, CoreSchema, GetJsonSchemaHandler, JsonSchemaValue, with_info_plain_validator_function, ) from starlette.datastructures import...
import dataclasses import datetime from collections import defaultdict, deque from decimal import Decimal from enum import Enum from ipaddress import ( IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network, ) from pathlib import Path, PurePath from re import Pattern fr...
from typing import Any, Dict, Optional, Sequence, Type, Union from pydantic import BaseModel, create_model from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.exceptions import WebSocketException as StarletteWebSocketException from typing_extensions import Annotated, Doc class HTT...
from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.utils import is_body_allowed_for_status_code from fastapi.websockets import WebSocket from starlette.exceptions import HTTPException from starlette.requests import Request fr...
import logging logger = logging.getLogger("fastapi")
import warnings from enum import Enum from typing import Any, Callable, Dict, List, Optional, Sequence, Union from fastapi.openapi.models import Example from pydantic.fields import FieldInfo from typing_extensions import Annotated, deprecated from ._compat import ( PYDANTIC_V2, PYDANTIC_VERSION_MINOR_TUPLE, ...
from typing import Any, Callable, Dict, List, Optional, Sequence, Union from fastapi import params from fastapi._compat import Undefined from fastapi.openapi.models import Example from typing_extensions import Annotated, Doc, deprecated _Unset: Any = Undefined def Path( # noqa: N802 default: Annotated[ ...
from starlette.requests import HTTPConnection as HTTPConnection # noqa: F401 from starlette.requests import Request as Request # noqa: F401
from typing import Any from starlette.responses import FileResponse as FileResponse # noqa from starlette.responses import HTMLResponse as HTMLResponse # noqa from starlette.responses import JSONResponse as JSONResponse # noqa from starlette.responses import PlainTextResponse as PlainTextResponse # noqa from starl...
import asyncio import dataclasses import email.message import inspect import json from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, AsyncIterator, Callable, Coroutine, Dict, List, Mapping, Optional, Sequence, Set, ...
from starlette.staticfiles import StaticFiles as StaticFiles # noqa
from starlette.templating import Jinja2Templates as Jinja2Templates # noqa
from starlette.testclient import TestClient as TestClient # noqa
import types from enum import Enum from typing import Any, Callable, Dict, Set, Type, TypeVar, Union from pydantic import BaseModel DecoratedCallable = TypeVar("DecoratedCallable", bound=Callable[..., Any]) UnionType = getattr(types, "UnionType", Union) ModelNameMap = Dict[Union[Type[BaseModel], Type[Enum]], str] Inc...
import re import warnings from dataclasses import is_dataclass from typing import ( TYPE_CHECKING, Any, Dict, MutableMapping, Optional, Set, Type, Union, cast, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( PYDANTIC_V2, BaseConfig, M...
from starlette.websockets import WebSocket as WebSocket # noqa from starlette.websockets import WebSocketDisconnect as WebSocketDisconnect # noqa from starlette.websockets import WebSocketState as WebSocketState # noqa
from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum from functools import lru_cache from typing import ( Any, Callable, Deque, Dict, FrozenSet, List, Mapping, Sequence, Set, Tuple, Type, Union, ) from ...
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production""" __version__ = "0.115.12" from starlette import status as status from .applications import FastAPI as FastAPI from .background import BackgroundTasks as BackgroundTasks from .datastructures import UploadFile as UploadFile fro...
from fastapi.cli import main main()
from dataclasses import dataclass, field from typing import Any, Callable, List, Optional, Sequence, Tuple from fastapi._compat import ModelField from fastapi.security.base import SecurityBase @dataclass class SecurityRequirement: security_scheme: SecurityBase scopes: Optional[Sequence[str]] = None @datacl...
import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Any, Callable, Coroutine, Dict, ForwardRef, List, Mapping, Optional, Sequence, Tuple, Type, Union, cast, ) impo...
null
from starlette.middleware.cors import CORSMiddleware as CORSMiddleware # noqa
from starlette.middleware.gzip import GZipMiddleware as GZipMiddleware # noqa
from starlette.middleware.httpsredirect import ( # noqa HTTPSRedirectMiddleware as HTTPSRedirectMiddleware, )
from starlette.middleware.trustedhost import ( # noqa TrustedHostMiddleware as TrustedHostMiddleware, )
from starlette.middleware.wsgi import WSGIMiddleware as WSGIMiddleware # noqa
from starlette.middleware import Middleware as Middleware
METHODS_WITH_BODY = {"GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"} REF_PREFIX = "#/components/schemas/" REF_TEMPLATE = "#/components/schemas/{model}"
import json from typing import Any, Dict, Optional from fastapi.encoders import jsonable_encoder from starlette.responses import HTMLResponse from typing_extensions import Annotated, Doc swagger_ui_default_parameters: Annotated[ Dict[str, Any], Doc( """ Default configurations for Swagger UI. ...
from enum import Enum from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Type, Union from fastapi._compat import ( PYDANTIC_V2, CoreSchema, GetJsonSchemaHandler, JsonSchemaValue, _model_rebuild, with_info_plain_validator_function, ) from fastapi.logger import logger from pyd...
import http.client import inspect import warnings from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, cast from fastapi import routing from fastapi._compat import ( GenerateJsonSchema, JsonSchemaValue, ModelField, Undefined, get_compat_model_name_map, get_definition...
null
from typing import Optional from fastapi.openapi.models import APIKey, APIKeyIn from fastapi.security.base import SecurityBase from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_403_FORBIDDEN from typing_extensions import Annotated, Doc class APIKe...
from fastapi.openapi.models import SecurityBase as SecurityBaseModel class SecurityBase: model: SecurityBaseModel scheme_name: str
import binascii from base64 import b64decode from typing import Optional from fastapi.exceptions import HTTPException from fastapi.openapi.models import HTTPBase as HTTPBaseModel from fastapi.openapi.models import HTTPBearer as HTTPBearerModel from fastapi.security.base import SecurityBase from fastapi.security.utils ...
from typing import Any, Dict, List, Optional, Union, cast from fastapi.exceptions import HTTPException from fastapi.openapi.models import OAuth2 as OAuth2Model from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel from fastapi.param_functions import Form from fastapi.security.base import SecurityBase from f...
from typing import Optional from fastapi.openapi.models import OpenIdConnect as OpenIdConnectModel from fastapi.security.base import SecurityBase from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_403_FORBIDDEN from typing_extensions import Annotated...
from typing import Optional, Tuple def get_authorization_scheme_param( authorization_header_value: Optional[str], ) -> Tuple[str, str]: if not authorization_header_value: return "", "" scheme, _, param = authorization_header_value.partition(" ") return scheme, param
from .api_key import APIKeyCookie as APIKeyCookie from .api_key import APIKeyHeader as APIKeyHeader from .api_key import APIKeyQuery as APIKeyQuery from .http import HTTPAuthorizationCredentials as HTTPAuthorizationCredentials from .http import HTTPBasic as HTTPBasic from .http import HTTPBasicCredentials as HTTPBasicC...
import asyncio import time from functools import wraps from .log import log_request_builder, logger class LifespanProtocol: error_transition = 'Invalid lifespan state transition' def __init__(self, callable): self.callable = callable self.event_queue = asyncio.Queue() self.event_star...
import json import pathlib from enum import Enum from typing import Any, Callable, List, Optional, Type, TypeVar, Union import click from .constants import HTTPModes, Interfaces, Loops, RuntimeModes, TaskImpl from .errors import FatalError from .http import HTTP1Settings, HTTP2Settings from .log import LogLevels from...
from enum import Enum class StrEnum(str, Enum): def __str__(self) -> str: return str(self.value) class Interfaces(StrEnum): ASGI = 'asgi' ASGINL = 'asginl' RSGI = 'rsgi' WSGI = 'wsgi' class HTTPModes(StrEnum): auto = 'auto' http1 = '1' http2 = '2' class RuntimeModes(StrEn...
class FatalError(Exception): ... class ConfigurationError(FatalError): ... class PidFileError(FatalError): ...
from dataclasses import dataclass from typing import Optional @dataclass class HTTP1Settings: header_read_timeout: int = 30_000 keep_alive: bool = True max_buffer_size: int = 8192 + 4096 * 100 pipeline_flush: bool = False @dataclass class HTTP2Settings: adaptive_window: bool = False initial_...
import copy import datetime import logging import logging.config import time from enum import Enum from typing import Any, Dict, Optional class LogLevels(str, Enum): critical = 'critical' error = 'error' warning = 'warning' warn = 'warn' info = 'info' debug = 'debug' notset = 'notset' lo...
import copyreg from ._granian import ListenerSpec as SocketSpec, SocketHolder copyreg.pickle(SocketHolder, lambda v: (SocketHolder, v.__getstate__())) copyreg.pickle(SocketSpec, lambda v: (SocketSpec, v.__getstate__()))
import time from enum import Enum from functools import wraps from typing import Optional, Union from ._granian import ( RSGIHeaders as Headers, RSGIHTTPProtocol as HTTPProtocol, # noqa: F401 RSGIProtocolClosed as ProtocolClosed, # noqa: F401 RSGIProtocolError as ProtocolError, # noqa: F401 RSGI...
import os import sys import time from functools import wraps from typing import Any, Callable, Dict, List, Tuple from .log import log_request_builder class Response: __slots__ = ['status', 'headers'] def __init__(self): self.status = 200 self.headers = [] def __call__(self, status: str,...
import sys _PYV = int(sys.version_info.major * 100 + sys.version_info.minor) _PY_312 = 312
from asyncio.tasks import ( Task as _Task, _enter_task as _aio_taskenter, _leave_task as _aio_taskleave, _register_task as _aio_taskreg, ) from functools import partial from ._granian import CallbackScheduler as _BaseCBScheduler def _future_watcher_wrapper(inner): async def future_watcher(watcher...
try: import anyio except ImportError: anyio = None try: import setproctitle except ImportError: setproctitle = None try: import watchfiles except ImportError: watchfiles = None
import os import re import sys import traceback from types import ModuleType from typing import Callable, List, Optional def get_import_components(path: str) -> List[Optional[str]]: return (re.split(r':(?![\\/])', path, 1) + [None])[:2] def prepare_import(path: str) -> str: path = os.path.realpath(path) ...
import asyncio import os import sys from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple WrappableT = Callable[..., Any] LoopBuilderT = Callable[..., asyncio.AbstractEventLoop] class Registry: __slots__ = ['_data'] def __init__(self): self._data: Dict[str, WrappableT] = {} d...
import signal import sys import threading from ._granian import WorkerSignal, WorkerSignalSync def set_main_signals(interrupt_handler, reload_handler=None): signals = [signal.SIGINT, signal.SIGTERM] if sys.platform == 'win32': signals.append(signal.SIGBREAK) for sig in signals: signal.si...
from typing import List, Optional, Tuple, Union class WebsocketMessage: kind: int data: Union[bytes, str] SSLCtx = Tuple[bool, Optional[str], Optional[str], Optional[str], Optional[str], List[str], bool]
from ._granian import __version__ # noqa: F401 from ._loops import loops # noqa: F401 from .server import Server as Granian # noqa: F401
from granian.cli import entrypoint entrypoint()
from __future__ import annotations import errno import multiprocessing import os import ssl import sys import threading import time from functools import partial from pathlib import Path from typing import Any, Callable, Dict, Generic, List, Optional, Sequence, Type, TypeVar from .._compat import _PY_312, _PYV from ....
import asyncio import multiprocessing from functools import wraps from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple from .._futures import _future_watcher_wrapper, _new_cbscheduler from .._granian import ASGIWorker, RSGIWorker, WorkerSignal from .._types import SSLCtx from ..asgi i...
import multiprocessing import socket import sys from functools import wraps from typing import Any, Callable, Dict, Optional, Tuple from .._futures import _future_watcher_wrapper, _new_cbscheduler from .._granian import ASGIWorker, RSGIWorker, SocketHolder, WSGIWorker from .._types import SSLCtx from ..asgi import Lif...
import sys import threading from functools import wraps from typing import Any, Callable, Dict, Optional, Tuple from .._futures import _future_watcher_wrapper, _new_cbscheduler from .._granian import ASGIWorker, RSGIWorker, WorkerSignal, WorkerSignalSync, WSGIWorker from .._loops import loops from .._types import SSLC...
from .._granian import BUILD_GIL from .mp import MPServer as MPServer from .mt import MTServer as MTServer Server = MPServer if BUILD_GIL else MTServer
# -*- coding: utf-8 -*- """ The root of the greenlet package. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function __all__ = [ '__version__', '_C_API', 'GreenletExit', 'error', 'getcurrent', 'greenlet', 'gettrace', 'settrace...
null
# -*- coding: utf-8 -*- """ If we have a run callable passed to the constructor or set as an attribute, but we don't actually use that (because ``__getattribute__`` or the like interferes), then when we clear callable before beginning to run, there's an opportunity for Python code to run. """ import greenlet g = None...
# -*- coding: utf-8 -*- """ Helper for testing a C++ exception throw aborts the process. Takes one argument, the name of the function in :mod:`_test_extension_cpp` to call. """ import sys import greenlet from greenlet.tests import _test_extension_cpp print('fail_cpp_exception is running') def run_unhandled_exception_...
""" Testing initialstub throwing an already started exception. """ import greenlet a = None b = None c = None main = greenlet.getcurrent() # If we switch into a dead greenlet, # we go looking for its parents. # if a parent is not yet started, we start it. results = [] def a_run(*args): #results.append('A') ...
# -*- coding: utf-8 -*- """ A test helper for seeing what happens when slp_switch() fails. """ # pragma: no cover import greenlet print('fail_slp_switch is running', flush=True) runs = [] def func(): runs.append(1) greenlet.getcurrent().parent.switch() runs.append(2) greenlet.getcurrent().parent.swi...
""" Uses a trace function to switch greenlets at unexpected times. In the trace function, we switch from the current greenlet to another greenlet, which switches """ import greenlet g1 = None g2 = None switch_to_g2 = False def tracefunc(*args): print('TRACE', *args) global switch_to_g2 if switch_to_g2: ...
""" Like fail_switch_three_greenlets, but the call into g1_run would actually be valid. """ import greenlet g1 = None g2 = None switch_to_g2 = True results = [] def tracefunc(*args): results.append(('trace', args[0])) print('TRACE', *args) global switch_to_g2 if switch_to_g2: switch_to_g2 = ...
""" Uses a trace function to switch greenlets at unexpected times. In the trace function, we switch from the current greenlet to another greenlet, which switches """ import greenlet g1 = None g2 = None switch_to_g2 = False def tracefunc(*args): print('TRACE', *args) global switch_to_g2 if switch_to_g2: ...
# Copyright (c) 2018 gevent community # Copyright (c) 2021 greenlet community # # This was originally part of gevent's test suite. The main author # (Jason Madden) vendored a copy of it into greenlet. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated docu...
from __future__ import print_function import gc import sys import unittest from functools import partial from unittest import skipUnless from unittest import skipIf from greenlet import greenlet from greenlet import getcurrent from . import TestCase from . import PY314 try: from contextvars import Context f...
from __future__ import print_function from __future__ import absolute_import import subprocess import unittest import greenlet from . import _test_extension_cpp from . import TestCase from . import WIN class CPPTests(TestCase): def test_exception_switch(self): greenlets = [] for i in range(4): ...
from __future__ import print_function from __future__ import absolute_import import sys import greenlet from . import _test_extension from . import TestCase # pylint:disable=c-extension-no-member class CAPITests(TestCase): def test_switch(self): self.assertEqual( 50, _test_extension.test_swi...
import gc import weakref import greenlet from . import TestCase from .leakcheck import fails_leakcheck # These only work with greenlet gc support # which is no longer optional. assert greenlet.GREENLET_USE_GC class GCTests(TestCase): def test_dead_circular_ref(self): o = weakref.ref(greenlet.greenlet(g...
from greenlet import greenlet from . import TestCase class genlet(greenlet): parent = None def __init__(self, *args, **kwds): self.args = args self.kwds = kwds def run(self): fn, = self.fn fn(*self.args, **self.kwds) def __iter__(self): return self def _...
from greenlet import greenlet from . import TestCase from .leakcheck import fails_leakcheck class genlet(greenlet): parent = None def __init__(self, *args, **kwds): self.args = args self.kwds = kwds self.child = None def run(self): # Note the function is packed in a tuple ...
import gc import sys import time import threading import unittest from abc import ABCMeta from abc import abstractmethod import greenlet from greenlet import greenlet as RawGreenlet from . import TestCase from . import RUNNING_ON_MANYLINUX from . import PY313 from . import PY314 from .leakcheck import fails_leakcheck...
# -*- coding: utf-8 -*- """ Tests for greenlets interacting with the CPython trash can API. The CPython trash can API is not designed to be re-entered from a single thread. But this can happen using greenlets, if something during the object deallocation process switches greenlets, and this second greenlet then causes ...
# -*- coding: utf-8 -*- """ Testing scenarios that may have leaked. """ from __future__ import print_function, absolute_import, division import sys import gc import time import weakref import threading import greenlet from . import TestCase from . import PY314 from .leakcheck import fails_leakcheck from .leakcheck ...
import greenlet from . import TestCase class Test(TestCase): def test_stack_saved(self): main = greenlet.getcurrent() self.assertEqual(main._stack_saved, 0) def func(): main.switch(main._stack_saved) g = greenlet.greenlet(func) x = g.switch() self.ass...
import sys from greenlet import greenlet from . import TestCase def switch(*args): return greenlet.getcurrent().parent.switch(*args) class ThrowTests(TestCase): def test_class(self): def f(): try: switch("ok") except RuntimeError: switch("ok")...
from __future__ import print_function import sys import greenlet import unittest from . import TestCase from . import PY312 # https://discuss.python.org/t/cpython-3-12-greenlet-and-tracing-profiling-how-to-not-crash-and-get-correct-results/33144/2 DEBUG_BUILD_PY312 = ( PY312 and hasattr(sys, 'gettotalrefcount'), ...
#! /usr/bin/env python from __future__ import absolute_import from __future__ import print_function import sys import os from unittest import TestCase as NonLeakingTestCase import greenlet # No reason to run this multiple times under leakchecks, # it doesn't do anything. class VersionTests(NonLeakingTestCase): d...
import gc import weakref import greenlet from . import TestCase class WeakRefTests(TestCase): def test_dead_weakref(self): def _dead_greenlet(): g = greenlet.greenlet(lambda: None) g.switch() return g o = weakref.ref(_dead_greenlet()) gc.collect() ...
# -*- coding: utf-8 -*- """ Tests for greenlet. """ import os import sys import unittest from gc import collect from gc import get_objects from threading import active_count as active_thread_count from time import sleep from time import time import psutil from greenlet import greenlet as RawGreenlet from greenlet i...
# We use native strings for all the re patterns, to take advantage of string # formatting, and then convert to bytestrings when compiling the final re # objects. # https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#whitespace # OWS = *( SP / HTAB ) # ; optional whitespace OWS = r"...
# This contains the main Connection class. Everything in h11 revolves around # this. from typing import ( Any, Callable, cast, Dict, List, Optional, overload, Tuple, Type, Union, ) from ._events import ( ConnectionClosed, Data, EndOfMessage, Event, Informatio...
# High level events that make up HTTP/1.1 conversations. Loosely inspired by # the corresponding events in hyper-h2: # # http://python-hyper.org/h2/en/stable/api.html#events # # Don't subclass these. Stuff will break. import re from abc import ABC from dataclasses import dataclass from typing import List, Tuple, U...
import re from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union from ._abnf import field_name, field_value from ._util import bytesify, LocalProtocolError, validate if TYPE_CHECKING: from ._events import Request try: from typing import Literal except ImportError: from typ...
# Code to read HTTP data # # Strategy: each reader is a callable which takes a ReceiveBuffer object, and # either: # 1) consumes some of it and returns an Event # 2) raises a LocalProtocolError (for consistency -- e.g. we call validate() # and it might raise a LocalProtocolError, so simpler just to always use # t...
import re import sys from typing import List, Optional, Union __all__ = ["ReceiveBuffer"] # Operations we want to support: # - find next \r\n or \r\n\r\n (\n or \n\n are also acceptable), # or wait until there is one # - read at-most-N bytes # Goals: # - on average, do this fast # - worst case, do this in O(n) whe...
################################################################ # The core state machine ################################################################ # # Rule 1: everything that affects the state machine and state transitions must # live here in this file. As much as possible goes into the table-based # representa...
from typing import Any, Dict, NoReturn, Pattern, Tuple, Type, TypeVar, Union __all__ = [ "ProtocolError", "LocalProtocolError", "RemoteProtocolError", "validate", "bytesify", ] class ProtocolError(Exception): """Exception indicating a violation of the HTTP/1.1 protocol. This as an abstra...
# This file must be kept very simple, because it is consumed from several # places -- it is imported by h11/__init__.py, execfile'd by setup.py, etc. # We use a simple scheme: # 1.0.0 -> 1.0.0+dev -> 1.1.0 -> 1.1.0+dev # where the +dev versions are never released into the wild, they're just what # we stick into the ...
# Code to read HTTP data # # Strategy: each writer takes an event + a write-some-bytes function, which is # calls. # # WRITERS is a dict describing how to pick a reader. It maps states to either: # - a writer # - or, for body writers, a dict of framin-dependent writer factories from typing import Any, Callable, Dict, ...
# A highish-level implementation of the HTTP/1.1 wire protocol (RFC 7230), # containing no networking code at all, loosely modelled on hyper-h2's generic # implementation of HTTP/2 (and in particular the h2.connection.H2Connection # class). There's still a bunch of subtle details you need to get right if you # want to ...