예제 #1
0
 def decorator(f: Func) -> Func:
     f.rpc_handler_info = dict(  # type: ignore
         shield=shield,
         raises=raises,
         schema=schema or validx.Dict({}),
         **kw)
     return f
예제 #2
0
파일: jwt.py 프로젝트: myackinc/Myack
 def payload_schema(self):
     return validx.Dict(
         {
             "sub": validx.Const(self.sub),
             "iat": validx.Float(min=0),
             "exp": validx.Float(min=0),
         },
         optional=None if self.ttl else ("exp",),
         extra=(validx.Str(), validx.Any()),
     )
예제 #3
0
파일: test_api.py 프로젝트: myackinc/Myack
    class Foo(Namespace):
        nested: Nested

        @middleware(1)
        async def middleware_1(self, handler, request):
            response = await handler(request)
            response.meta.setdefault("middlewares",
                                     []).append("Foo.middleware_1")
            return response

        @middleware(2)
        async def middleware_2(self, handler, request):
            response = await handler(request)
            response.meta.setdefault("middlewares",
                                     []).append("Foo.middleware_2")
            return response

        @handler(schema=validx.Dict({"x": validx.Int(), "y": validx.Int()}))
        async def sum(self, x, y, injection=None):
            return x + y, injection

        @handler(schema=validx.Dict({"x": validx.Int(), "y": validx.Int()}))
        async def incorrect_div(self, x, y, injection=None):
            return x / y, injection

        @handler(
            schema=validx.Dict({
                "x": validx.Int(),
                "y": validx.Int()
            }),
            raises=DivisionByZero,
        )
        async def div(self, x, y, injection=None):
            try:
                return x / y, injection
            except ZeroDivisionError:
                raise DivisionByZero()
예제 #4
0
class Entrypoint(DataObject, metaclass=ABCMeta):
    __slots__ = ()

    schema: typing.ClassVar[validx.Validator] = validx.Dict()

    @classmethod
    def load_native(cls: typing.Type[EntrypointType],
                    filename: str) -> EntrypointType:
        obj = cls()
        with open(filename, "rb", buffering=8192) as handle:
            obj.read(BinaryParser(handle))
        return obj

    def save_native(self, filename: str) -> None:
        with open(filename, "wb", buffering=8192) as handle:
            self.write(BinaryParser(handle))

    @classmethod
    def load_json(cls: typing.Type[EntrypointType],
                  filename: str) -> EntrypointType:
        obj = cls()
        with open(filename, "rb", buffering=8192) as handle:
            obj.from_json(handle.read().decode())
        return obj

    def save_json(self, filename: str, **kwargs) -> None:
        with open(filename, "wb", buffering=8192) as handle:
            handle.write(self.to_json(**kwargs).encode())

    def to_json(self, **kwargs) -> str:
        return json.dumps(self.serialize(), **kwargs)

    @classmethod
    def from_json(cls: typing.Type[EntrypointType],
                  data: str) -> EntrypointType:
        obj = cls()
        decoded_data = json.loads(data)

        try:
            obj.schema(decoded_data)
        except validx.exc.ValidationError as e:
            e.sort()
            rows = [f"{c}: {m}" for c, m in validx.exc.format_error(e)]
            raise OMFInvalidDataException("\n".join(rows))

        return obj.unserialize(decoded_data)
예제 #5
0
@dataclass
class Contract:
    name: str
    description: str
    validate_in: v.Dict
    validate_out: Union[v.Dict, v.List]


_contracts: Tuple[Contract, ...] = (
    Contract(
        name="push_tasks",
        description="Data about the tasks that ran on a given push.",
        validate_in=v.Dict(
            {
                "branch": v.Str(),
                "rev": v.Str(),
            }
        ),
        validate_out=v.List(
            v.Dict(
                {
                    "id": v.Str(),
                    "label": v.Str(),
                    "state": v.Str(
                        options=[
                            "completed",
                            "running",
                            "pending",
                            "unscheduled",
                            "exception",
                        ]
예제 #6
0
import validx as v

city_schema: v.Validator = v.Dict(
    {
        "location": v.Tuple(v.Float(min=-90, max=90), v.Float(min=-180,
                                                              max=180)),
        "name": v.Str(),
        "alt_names": v.List(v.Str(), unique=True),
        "population": v.Dict({
            "city": v.Int(min=0),
            "metro": v.Int(min=0)
        }),
    },
    extra=(v.Str(), v.Any()),
)
예제 #7
0
파일: test_data.py 프로젝트: mozilla/mozci
from mozci import data
from mozci.data.base import DataHandler, DataSource
from mozci.data.contract import Contract
from mozci.errors import (
    ContractNotFilled,
    ContractNotFound,
    InvalidSource,
    SourcesNotFound,
)

FAKE_CONTRACTS = (
    Contract(
        name="foo",
        description="test",
        validate_in=v.Dict({"label": v.Str()}),
        validate_out=v.Dict({"count": v.Int()}),
    ),
    Contract(
        name="bar",
        description="test",
        validate_in=v.Dict({"desc": v.Str()}),
        validate_out=v.Dict({"amount": v.Int()}),
    ),
    Contract(
        name="baz",
        description="test",
        validate_in=v.Dict({"id": v.Str()}),
        validate_out=v.Dict({"sum": v.Int()}),
    ),
    Contract(
예제 #8
0
class Request:

    schema: ClassVar[validx.Validator] = validx.Dict(
        {
            "id":
            validx.Int(),
            "method":
            validx.Str(encoding="ascii"),
            "params":
            validx.Dict(extra=(validx.Str(), validx.Any())),
            "meta":
            validx.Dict(
                {
                    "version":
                    validx.Tuple(
                        validx.Int(min=0), validx.Int(min=0), nullable=True),
                },
                optional=("version", ),
                extra=(validx.Str(), validx.Any()),
            ),
        },
        defaults={
            "params": {},
            "meta": {}
        },
    )

    id: int
    method: str
    meta: Dict[str, Any]
    params: Dict[str, Any]

    middlewares: List[Middleware]
    injections: Dict[str, Any]

    handler: Optional[Callable[..., Awaitable[Any]]]
    handler_info: Dict[str, Any]

    def __init__(
        self,
        id: int,
        method: str,
        meta: Dict[str, Any] = None,
        params: Dict[str, Any] = None,
    ) -> None:
        self.id = id
        self.method = method
        self.meta = meta if meta is not None else {}
        self.params = params if params is not None else {}

        self.middlewares = []
        self.injections = {}

        self.handler = None
        self.handler_info = {}

    @classmethod
    def load(cls, payload: Dict[str, Any]) -> "Request":
        try:
            return cls(**cls.schema(payload))
        except validx.exc.ValidationError as e:
            raise RPCInvalidRequest(reason=cls.format_schema_error(e))

    @classmethod
    def format_schema_error(
            cls, error: validx.exc.ValidationError) -> Dict[str, str]:
        return dict(validx.exc.format_error(error))

    @cached_property
    def handler_signature(self) -> inspect.Signature:
        assert self.handler is not None
        return inspect.signature(self.handler)

    def response(
        self,
        result: Any = None,
        meta: Dict[str, Any] = None,
        error: BaseError = None,
        warnings: List[BaseWarning] = None,
    ) -> Response:
        return Response(id=self.id,
                        meta=meta,
                        result=result,
                        error=error,
                        warnings=warnings)
예제 #9
0
파일: jwt.py 프로젝트: myackinc/Myack
 def header_schema(self):
     return validx.Dict(
         {"typ": validx.Const("JWT"), "alg": validx.Const(self.alg)},
         extra=(validx.Str(), validx.Any()),
     )
예제 #10
0

@dataclass
class Contract:
    name: str
    description: str
    validate_in: v.Dict
    validate_out: Union[v.Dict, v.List]


_contracts: Tuple[Contract, ...] = (
    Contract(
        name="push_tasks",
        description="Data about the tasks that ran on a given push.",
        validate_in=v.Dict({
            "branch": v.Str(),
            "rev": v.Str(),
        }),
        validate_out=v.List(
            v.Dict(
                {
                    "id":
                    v.Str(),
                    "label":
                    v.Str(),
                    "state":
                    v.Str(options=[
                        "completed",
                        "running",
                        "pending",
                        "unscheduled",
                        "exception",