def ssr( *, props: Type[P], params: None = None ) -> Callable[[NoArgsView[P]], Callable[ [Arg(HttpRequest, 'request'), KwArg(Any)], HttpResponse]]: ...
def wrap_with_jsx( original: View[K, P] ) -> Callable[ [Arg(HttpRequest, 'request'), KwArg(Any)], HttpResponse]: def wrapper(request: HttpRequest, **kwargs: Any) -> HttpResponse: props = original(request, cast(Any, params)(**kwargs)) template_name = to_camel_case(original.__name__) return render_jsx(request, template_name, props) return wrapper
def help_factory( self, parser: SlackArgumentParser, **kwarg: Any ) -> Callable[[Arg(SlackEventContextMessage, "context" ), KwArg(Any)], None]: def help_func(context: SlackEventContextMessage, **kwarg: Any) -> None: text = "" if "message" in kwarg: text += kwarg["message"] text += "\n" text += parser.format_help() context.reply_ephemeral(text=text) return help_func
def ssr( *, props: Type[P], params: Optional[Type[K]] = None ) -> Union[Callable[[NoArgsView[P]], Callable[ [Arg(HttpRequest, 'request'), KwArg(Any)], HttpResponse]], Callable[ [View[K, P]], Callable[[Arg(HttpRequest, 'request' ), KwArg(Any)], HttpResponse]], ]: type_registry[props.__name__] = props # type: ignore def no_args_wrap_with_jsx( original: NoArgsView[P] ) -> Callable[ [Arg(HttpRequest, 'request'), KwArg(Any)], HttpResponse]: def wrapper(request: HttpRequest, **kwargs: Any) -> HttpResponse: props = original(request) template_name = to_camel_case(original.__name__) return render_jsx(request, template_name, props) return wrapper def wrap_with_jsx( original: View[K, P] ) -> Callable[ [Arg(HttpRequest, 'request'), KwArg(Any)], HttpResponse]: def wrapper(request: HttpRequest, **kwargs: Any) -> HttpResponse: props = original(request, cast(Any, params)(**kwargs)) template_name = to_camel_case(original.__name__) return render_jsx(request, template_name, props) return wrapper if params is None: return no_args_wrap_with_jsx else: return wrap_with_jsx
try: import yelp_meteorite except ImportError: # Sorry to any non-yelpers but you won't # get metrics emitted as our metrics lib # is currently not open source yelp_meteorite = None # Marathon REST API: # https://github.com/mesosphere/marathon/blob/master/REST.md#post-v2apps log = logging.getLogger(__name__) LogDeployError = Callable[ [Arg(str, "errormsg"), DefaultNamedArg(str, "level")], None] LogBounceAction = Callable[ [Arg(str, "line"), DefaultNamedArg(str, "level")], None] def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Creates marathon jobs.") parser.add_argument( "service_instance_list", nargs="+", help="The list of marathon service instances to create or update", metavar="SERVICE%sINSTANCE" % SPACER, ) parser.add_argument( "-d",
from typing import Callable, NamedTuple, Optional from mypy_extensions import Arg, DefaultArg class TxoKeyType(NamedTuple): tx_hash: bytes tx_index: int WaitingUpdateCallback = Callable[[Arg(bool, "advance"), DefaultArg(Optional[str], "message")], None]
'Response', 'ResourceOptions', 'View', 'ViewHandlerMethod', 'ViewHandlerFun', 'ViewDecorator', 'PageArg', 'HttpClientT', 'Web', 'CacheBackendT', 'CacheT', 'BlueprintT', ] ViewHandlerMethod = Callable[ [Arg(Request), VarArg(Any), KwArg(Any)], Awaitable[Response], ] ViewHandler2ArgsFun = Callable[ [Arg(View), Arg(Request)], Union[Coroutine[Any, Any, Response], Awaitable[Response]], ] ViewHandlerVarArgsFun = Callable[ [Arg(View), Arg(Request), VarArg(Any), KwArg(Any)], Union[Coroutine[Any, Any, Response], Awaitable[Response]], ] ViewHandlerFun = Union[ViewHandler2ArgsFun, ViewHandlerVarArgsFun]
) if sentSecurely or not request.isSecure(): # Do not cache the insecure session on the secure request, thanks. request.setComponent(ISession, session) returnValue(session) _procureProcurerType = Union[Callable[[Any], ISessionProcurer], Callable[[], ISessionProcurer]] _kleinRenderable = Any _routeCallable = Any _kleinCallable = Callable[..., _kleinRenderable] _kleinDecorator = Callable[[_kleinCallable], _kleinCallable] _requirerResult = Callable[ [Arg(_routeCallable, 'route'), KwArg(Any)], Callable[[_kleinCallable], _kleinCallable]] class AuthorizationDenied(Resource, object): def __init__(self, interface, instance): # type: (IInterface, Any) -> None self._interface = interface super(AuthorizationDenied, self).__init__() def render(self, request): # type: (IRequest) -> bytes request.setResponseCode(UNAUTHORIZED) return "{} DENIED".format(qual(self._interface)).encode('utf-8')
) if sentSecurely or not request.isSecure(): # Do not cache the insecure session on the secure request, thanks. request.setComponent(ISession, session) # type: ignore[misc] returnValue(session) _procureProcurerType = Union[Callable[[Any], ISessionProcurer], Callable[[], ISessionProcurer]] _kleinRenderable = Any _routeCallable = Any _kleinCallable = Callable[..., _kleinRenderable] _kleinDecorator = Callable[[_kleinCallable], _kleinCallable] _requirerResult = Callable[ [Arg(_routeCallable, "route"), KwArg(Any)], Callable[[_kleinCallable], _kleinCallable], ] class AuthorizationDenied(Resource, object): def __init__(self, interface, instance): # type: (IInterface, Any) -> None self._interface = interface super(AuthorizationDenied, self).__init__() def render(self, request): # type: (IRequest) -> bytes request.setResponseCode(UNAUTHORIZED) return "{} DENIED".format(qual(self._interface)).encode("utf-8")
from sentry_sdk.utils import capture_internal_exceptions, event_from_exception from sentry_sdk.integrations import Integration from sentry_sdk._types import MYPY if MYPY: from typing import Callable from typing import Any from typing import Type from types import TracebackType from mypy_extensions import Arg Excepthook = Callable[[ Arg(Type[BaseException], "type_"), Arg(BaseException, "value"), Arg(TracebackType, "traceback"), ], None, ] class ExcepthookIntegration(Integration): identifier = "excepthook" always_run = False def __init__(self, always_run=False): # type: (bool) -> None if not isinstance(always_run, bool): raise ValueError(
from paasta_tools.utils import InvalidInstanceConfig from paasta_tools.utils import InvalidJobNameError from paasta_tools.utils import load_system_paasta_config from paasta_tools.utils import NoConfigurationForServiceError from paasta_tools.utils import NoDeploymentsAvailable from paasta_tools.utils import NoDockerImageError from paasta_tools.utils import SPACER from paasta_tools.utils import SystemPaastaConfig # Marathon REST API: # https://github.com/mesosphere/marathon/blob/master/REST.md#post-v2apps log = logging.getLogger(__name__) LogDeployError = Callable[ [Arg(str, 'errormsg'), DefaultNamedArg(str, 'level')], None] LogBounceAction = Callable[ [Arg(str, 'line'), DefaultNamedArg(str, 'level')], None] def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description='Creates marathon jobs.') parser.add_argument( 'service_instance_list', nargs='+', help="The list of marathon service instances to create or update", metavar="SERVICE%sINSTANCE" % SPACER, ) parser.add_argument( '-d',
try: import yelp_meteorite except ImportError: # Sorry to any non-yelpers but you won't # get metrics emitted as our metrics lib # is currently not open source yelp_meteorite = None # Marathon REST API: # https://github.com/mesosphere/marathon/blob/master/REST.md#post-v2apps log = logging.getLogger(__name__) LogDeployError = Callable[[Arg(str, "errormsg"), DefaultNamedArg(str, "level")], None] LogBounceAction = Callable[[Arg(str, "line"), DefaultNamedArg(str, "level")], None] def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Creates marathon jobs.") parser.add_argument( "service_instance_list", nargs="+", help="The list of marathon service instances to create or update", metavar="SERVICE%sINSTANCE" % SPACER, ) parser.add_argument( "-d",
log = logging.getLogger(__name__) log.addHandler(logging.NullHandler()) logging.getLogger("requests").setLevel(logging.WARNING) ZK_LOCK_CONNECT_TIMEOUT_S = 10.0 # seconds to wait to connect to zookeeper ZK_LOCK_PATH = "/bounce" WAIT_CREATE_S = 3 WAIT_DELETE_S = 5 BounceMethodResult = TypedDict("BounceMethodResult", { "create_app": bool, "tasks_to_drain": Set }) BounceMethod = Callable[[ Arg(BounceMethodConfigDict, "new_config"), Arg(bool, "new_app_running"), Arg(Collection, "happy_new_tasks"), Arg(Sequence, "old_non_draining_tasks"), DefaultArg(float, "margin_factor"), ], BounceMethodResult, ] _bounce_method_funcs: Dict[str, BounceMethod] = {} def register_bounce_method( name: str) -> Callable[[BounceMethod], BounceMethod]: """Returns a decorator that registers that bounce function at a given name so get_bounce_method_func can find it.""" def outer(bounce_func: BounceMethod): _bounce_method_funcs[name] = bounce_func
'Request', 'Response', 'View', 'ViewHandlerMethod', 'ViewHandlerFun', 'ViewDecorator', 'PageArg', 'HttpClientT', 'Web', 'CacheBackendT', 'CacheT', 'BlueprintT', ] ViewHandlerMethod = Callable[ [Arg(Request), VarArg(Any), KwArg(Any)], Awaitable[Response], ] ViewHandler2ArgsFun = Callable[[Arg(View), Arg(Request)], Union[Coroutine[Any, Any, Response], Awaitable[Response]], ] ViewHandlerVarArgsFun = Callable[ [Arg(View), Arg(Request), VarArg(Any), KwArg(Any)], Union[Coroutine[Any, Any, Response], Awaitable[Response]], ] ViewHandlerFun = Union[ViewHandler2ArgsFun, ViewHandlerVarArgsFun] ViewGetHandler = ViewHandlerFun # XXX compat ViewDecorator = Callable[[ViewHandlerFun], ViewHandlerFun] RoutedViewGetHandler = ViewDecorator # XXX compat PageArg = Union[Type[View], ViewHandlerFun]
def ssr( *, props: Type[P], params: Type[K] ) -> Callable[[View[K, P]], Callable[ [Arg(HttpRequest, 'request'), KwArg(Any)], HttpResponse]]: ...
# -*- coding: utf-8 -*- import typing from mypy_extensions import Arg try: from typing import NoReturn except ImportError: NoReturn = None # type: ignore Func = typing.Callable[..., typing.Any] FuncType = typing.TypeVar('FuncType', bound=Func) JSONDict = typing.Dict[typing.Text, typing.Any] MarshalingMethod = typing.Callable[[Arg(typing.Any, 'value')], typing.Any] UnmarshalingMethod = typing.Callable[[Arg(typing.Any, 'value')], typing.Any]
from paasta_tools.utils import DEFAULT_SOA_DIR from paasta_tools.utils import InstanceConfig_T from paasta_tools.utils import list_services from paasta_tools.utils import load_system_paasta_config from paasta_tools.utils import SPACER from paasta_tools.utils import SystemPaastaConfig try: import yelp_meteorite except ImportError: yelp_meteorite = None log = logging.getLogger(__name__) CheckServiceReplication = Callable[[ Arg(InstanceConfig_T, "instance_config"), Arg(Sequence[Union[MarathonTask, V1Pod]], "all_tasks_or_pods"), Arg(Any, "replication_checker"), NamedArg(bool, "dry_run"), ], Optional[bool], ] def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument( "-d", "--soa-dir", dest="soa_dir", metavar="SOA_DIR", default=DEFAULT_SOA_DIR, help="define a different soa config directory",
TargetFunctionT = TypeVar('TargetFunctionT', bound=Callable[..., Any]) # TargetReturnT]) """Type for decorated function""" #FUTURE: Currently (mypy 0.800) not possible to declare generic `TypeVar` # https://github.com/python/mypy/issues/8278 # Would need to use Callable[..., TargetReturnT] directly. TargetClassT = TypeVar('TargetClassT', bound=object) """Type for decorated class""" TargetT = TypeVar('TargetT', Callable[..., Any], Type[object]) """Type for decorated function or class""" TargetFunctionWrapper = Callable[[ Arg(Callable[..., TargetReturnT], 'target'), VarArg(), KwArg() ], TargetReturnT] # Callable[[TargetFunctionT, ...], TargetReturnT] """ Generic type for function that calls the decorated function :param TargetReturnT: Return type of the decorated function. """ TargetMethodWrapper = Callable[[ Arg(Callable[..., TargetReturnT], 'target'), Arg(TargetClassT, 'instance'), Arg(Type[TargetClassT], 'cls'), VarArg(), KwArg() ], TargetReturnT] # Callable[[TargetFunctionT, ...], TargetReturnT]
from paasta_tools.kubernetes_tools import get_all_nodes from paasta_tools.kubernetes_tools import get_all_pods from paasta_tools.kubernetes_tools import KubeClient from paasta_tools.kubernetes_tools import V1Pod from paasta_tools.paasta_service_config_loader import PaastaServiceConfigLoader from paasta_tools.smartstack_tools import KubeSmartstackReplicationChecker from paasta_tools.utils import DEFAULT_SOA_DIR from paasta_tools.utils import InstanceConfig_T from paasta_tools.utils import list_services from paasta_tools.utils import load_system_paasta_config from paasta_tools.utils import SPACER log = logging.getLogger(__name__) CheckServiceReplication = Callable[[ Arg(InstanceConfig_T, "instance_config"), Arg(Sequence[V1Pod], "all_pods"), Arg(KubeSmartstackReplicationChecker, "smartstack_replication_checker"), ], None, ] def parse_args() -> argparse.Namespace: epilog = "PERCENTAGE is an integer value representing the percentage of available to expected instances" parser = argparse.ArgumentParser(epilog=epilog) parser.add_argument( "-d", "--soa-dir", dest="soa_dir", metavar="SOA_DIR", default=DEFAULT_SOA_DIR,
import logging from typing import Any, Callable, List # from typing import Iterator, List, Tuple, NewType, Dict, Callable, Any from mypy_extensions import KwArg, Arg from coinpy.core import JsonDict from coinpy.core.crypto import Serializable from coinpy.core.transaction import Transaction from coinpy.core.block import Block from coinpy.core.errors import (ValidationError) logger = logging.getLogger(__name__) CommandHandler = Callable[[Arg(Any, 'ctx'), KwArg(Any)], None] class Command(Serializable): name = 'undefined' def __init__(self, **params: Any) -> None: self.params = params def _serialize(self) -> JsonDict: return { 'name': self.name, 'params': self.params, } def validate(self) -> None: if self.name == 'undefined':
pass class InsertOptions(OptionBlock, ServerDurableOption, ClientDurableOption): pass class GetFromReplicaOptions(OptionBlock): pass T = TypeVar('T', bound='CBCollection') R = TypeVar("R") RawCollectionMethodDefault = Callable[ [Arg('CBCollection', 'self'), Arg(str, 'key'), VarArg(OptionBlockDeriv), KwArg(Any)], R] RawCollectionMethodInt = Callable[ [Arg('CBCollection', 'self'), Arg(str, 'key'), int, VarArg(OptionBlockDeriv), KwArg(Any)], R] RawCollectionMethod = Union[RawCollectionMethodDefault, RawCollectionMethodInt] RawCollectionMethodSpecial = TypeVar('RawCollectionMethodSpecial',bound=RawCollectionMethod) def _get_result_and_inject(func # type: RawCollectionMethod ): # type: (...) ->RawCollectionMethod result = _inject_scope_and_collection(get_result_wrapper(func)) result.__doc__=func.__doc__ result.__name__=func.__name__ return result
if TYPE_CHECKING: # pylint: disable=cyclic-import import bs4 # noqa import gluetool # noqa import gluetool.sentry # noqa # Type definitions # pylint: disable=invalid-name ExceptionInfoType = Union[ Tuple[Optional[type], Optional[BaseException], Optional[TracebackType]], # returned by sys.exc_info() Tuple[None, None, None] ] LoggingFunctionType = Callable[ [ Arg(str), DefaultNamedArg(ExceptionInfoType, 'exc_info'), DefaultNamedArg(Dict[str, Any], 'extra'), DefaultNamedArg(bool, 'sentry') ], None ] ContextInfoType = Tuple[int, Any] BLOB_HEADER = '---v---v---v---v---v---' BLOB_FOOTER = '---^---^---^---^---^---' # Default log level is logging.INFO or logging.DEBUG if GLUETOOL_DEBUG environment variable is set DEFAULT_LOG_LEVEL = logging.DEBUG if os.getenv('GLUETOOL_DEBUG') else logging.INFO
new objects in middleware """ status_code: int headers: Headers body: bytes class HttpDisconnect(NamedTuple): pass # Just the request and response HttpRequestResponseView = Callable[[HttpRequest], Awaitable[HttpResponse]] HttpView = Union[Callable[[HttpRequest, Arg(str)], Awaitable[HttpResponse]], HttpRequestResponseView] # if the route is just a view it accepts all methods. # If it's a dict, it's the specified method(s) HttpMethodView = Union[HttpView, dict[str, HttpView]] HttpRoute = tuple[RouteMatcher, HttpMethodView] HttpProtoRouteThreeTuple = tuple[MatcherOrStr, set[str], HttpView] HttpProtoRouteTwoTuple = tuple[MatcherOrStr, HttpMethodView] HttpProtoRoute = Union[HttpProtoRouteTwoTuple, HttpProtoRouteThreeTuple] HttpMiddlewareFunc = Callable[[HttpRequestResponseView, HttpRequest], Awaitable[HttpResponse]]
self.close_connection(connection) class Group(Host): pass class Hosts(Dict[str, Host]): pass class Groups(Dict[str, Group]): pass TransformFunction = Callable[[Arg(Host), KwArg(Any)], None] FilterObj = Callable[[Arg(Host), KwArg(Any)], bool] class Inventory(object): __slots__ = ("hosts", "groups", "defaults") def __init__( self, hosts: Hosts, groups: Optional[Groups] = None, defaults: Optional[Defaults] = None, transform_function: TransformFunction = None, transform_function_options: Optional[Dict[str, Any]] = None, ) -> None: self.hosts = hosts
NamedArg(Optional[str], "uid"), NamedArg(Optional[str], "name"), NamedArg(Optional[str], "namespace"), NamedArg(patches.Patch, "patch"), NamedArg(diffs.Diff, "diff"), NamedArg(Optional[Union[bodies.BodyEssence, Any]], "old"), NamedArg(Optional[Union[bodies.BodyEssence, Any]], "new"), NamedArg(typedefs.Logger, "logger"), NamedArg(Any, "memo"), DefaultNamedArg(Any, "param"), KwArg(Any), ], bool # strictly sync, no async! ] MetaFilterFn = Callable[[ Arg(Any, "value"), NamedArg(str, "type"), NamedArg(bodies.Annotations, "annotations"), NamedArg(bodies.Labels, "labels"), NamedArg(bodies.Body, "body"), NamedArg(bodies.Meta, "meta"), NamedArg(bodies.Spec, "spec"), NamedArg(bodies.Status, "status"), NamedArg(references.Resource, "resource"), NamedArg(Optional[str], "uid"), NamedArg(Optional[str], "name"), NamedArg(Optional[str], "namespace"), NamedArg(patches.Patch, "patch"), NamedArg(typedefs.Logger, "logger"), NamedArg(Any, "memo"), DefaultNamedArg(Any, "param"),
if byteorder == 'big': pass elif byteorder == 'little': bytes = bytes[::-1] else: raise ValueError("byteorder must be either 'little' or 'big'") hex_str = codecs.encode(bytes, 'hex') # type: ignore return int(hex_str, 16) # Make this cast since Python 2 doesn't have syntax for default # named arguments. Hence, must cast so Mypy thinks it matches the # original function. int_from_bytes = cast( Callable[[ Arg(Sequence[int], 'bytes'), Arg(str, 'byteorder'), DefaultNamedArg(bool, 'signed') ], int], _int_from_bytes) def re_compile_full(pattern, flags=0): # type: (AnyStr, int) -> Pattern """ Create compiled regular expression such that it matches the entire string. Calling re.match on the output of this function is equivalent to calling re.fullmatch on its input. This is needed to support Python 2. (On Python 3, we would just call re.fullmatch.) Kudos: https://stackoverflow.com/a/30212799
ZK_LOCK_CONNECT_TIMEOUT_S = 10.0 # seconds to wait to connect to zookeeper ZK_LOCK_PATH = '/bounce' WAIT_CREATE_S = 3 WAIT_DELETE_S = 5 BounceMethodResult = TypedDict( 'BounceMethodResult', { "create_app": bool, "tasks_to_drain": Set, }, ) BounceMethod = Callable[[ Arg(BounceMethodConfigDict, 'new_config'), Arg(bool, 'new_app_running'), Arg(Collection, 'happy_new_tasks'), Arg(Sequence, 'old_non_draining_tasks'), DefaultArg(float, 'margin_factor'), ], BounceMethodResult] _bounce_method_funcs: Dict[str, BounceMethod] = {} def register_bounce_method( name: str) -> Callable[[BounceMethod], BounceMethod]: """Returns a decorator that registers that bounce function at a given name so get_bounce_method_func can find it.""" def outer(bounce_func: BounceMethod): _bounce_method_funcs[name] = bounce_func
'Request', 'Response', 'View', 'ViewHandlerMethod', 'ViewHandlerFun', 'ViewDecorator', 'PageArg', 'HttpClientT', 'Web', 'CacheBackendT', 'CacheT', 'BlueprintT', ] ViewHandlerMethod = Callable[ [Arg(Request), VarArg(Any), KwArg(Any)], Awaitable[Response], ] ViewHandlerFun = Callable[ [Arg(View), Arg(Request), VarArg(Any), KwArg(Any)], Awaitable[Response], ] ViewGetHandler = ViewHandlerFun # XXX compat ViewDecorator = Callable[[ViewHandlerFun], ViewHandlerFun] RoutedViewGetHandler = ViewDecorator # XXX compat PageArg = Union[Type[View], ViewHandlerFun] RouteDecoratorRet = Callable[[PageArg], PageArg] class CacheBackendT(ServiceT): @abc.abstractmethod def __init__(self,
if sentSecurely or not request.isSecure(): # Do not cache the insecure session on the secure request, thanks. request.setComponent(ISession, session) returnValue(session) _procureProcurerType = Union[ Callable[[Any], ISessionProcurer], Callable[[], ISessionProcurer] ] _kleinRenderable = Any _routeCallable = Any _kleinCallable = Callable[..., _kleinRenderable] _kleinDecorator = Callable[[_kleinCallable], _kleinCallable] _requirerResult = Callable[[Arg(_routeCallable, 'route'), KwArg(Any)], Callable[[_kleinCallable], _kleinCallable]] class AuthorizationDenied(Resource, object): def __init__(self, interface, instance): # type: (IInterface, Any) -> None self._interface = interface super(AuthorizationDenied, self).__init__() def render(self, request): # type: (IRequest) -> bytes request.setResponseCode(UNAUTHORIZED) return "{} DENIED".format(qual(self._interface)).encode('utf-8')
if byteorder == 'big': pass elif byteorder == 'little': bytes = bytes[::-1] else: raise ValueError("byteorder must be either 'little' or 'big'") hex_str = codecs.encode(bytes, 'hex') # type: ignore return int(hex_str, 16) # Make this cast since Python 2 doesn't have syntax for default # named arguments. Hence, must cast so Mypy thinks it matches the # original function. int_from_bytes = cast(Callable[[Arg(Sequence[int], 'bytes'), Arg(str, 'byteorder'), DefaultNamedArg(bool, 'signed')], int], _int_from_bytes) def re_compile_full(pattern, flags=0): # type: (AnyStr, int) -> Pattern """ Create compiled regular expression such that it matches the entire string. Calling re.match on the output of this function is equivalent to calling re.fullmatch on its input. This is needed to support Python 2. (On Python 3, we would just call re.fullmatch.) Kudos: https://stackoverflow.com/a/30212799