コード例 #1
0
ファイル: response.py プロジェクト: armonge/apidaora
def as_asgi(response: Response) -> AsgiResponse:
    headers_field = type(response).__dataclass_fields__[  # type: ignore
        'headers']
    headers: AsgiHeaders = (as_asgi_headers(
        response.headers, headers_field.type) if response.headers else [])
    body: bytes = b''

    if response.body:
        if (type(response).__content_type__  # type: ignore
                == JSONResponse.__content_type__):
            body = dataclass_asjson(response.body)

        elif not isinstance(response.body, bytes):
            body = str(response.body).encode()

        if body:
            if type(response).__content_type__:  # type: ignore
                headers.append((
                    b'Content-Type',
                    type(response).__content_type__.value.encode(
                    ),  # type: ignore
                ))

            headers.append((b'Content-Length', str(len(body)).encode()))

    return AsgiResponse(
        status_code=response.__status_code__,  # type: ignore
        headers=headers,
        body=body,
    )
コード例 #2
0
def tests_should_serialize_all_fields_with_choosen_deserialize_fields():
    @jsondaora(deserialize_fields=('test2', ))
    @dataclass
    class FakeDataclass:
        test: int
        test2: str

    dataclass_ = asdataclass({'test': '1', 'test2': 2}, FakeDataclass)

    assert dataclass_asjson(dataclass_) == b'{"test":"1","test2":"2"}'
コード例 #3
0
ファイル: api.py プロジェクト: moaddib666/asyncapi-python
    def parse_message(self, channel_id: str, message: Any) -> Any:
        type_ = self.publish_payload_type(channel_id)

        if type_:
            if issubclass(type_, dict):
                return typed_dict_asjson(message, type_)

            if not isinstance(message, type_):
                raise InvalidMessageError(message, type_)

            return dataclass_asjson(message)

        return message
コード例 #4
0
class Person:
    name: str
    age: int

    class Music:
        name: str

    musics: List[Music]


jsondict = dict(name='John', age=40, musics=[dict(name='Imagine')])
person = asdataclass(jsondict, Person)

print('dataclass:')
print(person)
print(dataclass_asjson(person))
print()

# TypedDict


@jsondaora(serialize_fields=('age'))
class Person(TypedDict):
    name: str
    age: int

    class Music(TypedDict):
        name: str

    musics: List[Music]
コード例 #5
0
ファイル: factory.py プロジェクト: dutradda/apidaora
    async def build_asgi_output(
        request: Request,
        controller_output: Any,
        status: HTTPStatus = HTTPStatus.OK,
        headers: Optional[Sequence[Header]] = None,
        content_type: Optional[ContentType] = ContentType.APPLICATION_JSON,
        return_type_: Any = None,
        middlewares: Optional[Middlewares] = None,
    ) -> ASGICallableResults:
        while iscoroutine(controller_output):
            controller_output = await controller_output

        if return_type_ is None and return_type:
            return_type_ = return_type

        if middlewares:
            if not isinstance(controller_output, Response):
                controller_output = Response(
                    body=controller_output,
                    status=status,
                    headers=headers,
                    content_type=content_type,
                )

            for middleware in middlewares.post_execution:
                middleware(request, controller_output)

        if isinstance(controller_output, Response):
            return build_asgi_output(
                request,
                controller_output['body'],
                controller_output['status'],
                controller_output['headers'],
                controller_output['content_type'],
                controller_output.__annotations__.get('body'),
            )

        elif isinstance(controller_output, dict):
            if return_type_:
                body = typed_dict_asjson(controller_output, return_type_)
            else:
                body = orjson.dumps(controller_output)

        elif (is_dataclass(controller_output)
              or isinstance(controller_output, tuple)
              or isinstance(controller_output, list)):
            body = dataclass_asjson(controller_output)

        elif (isinstance(controller_output, str)
              or isinstance(controller_output, int)
              or isinstance(controller_output, bool)
              or isinstance(controller_output, float)
              or isinstance(controller_output, bytes)):
            if content_type == ContentType.APPLICATION_JSON:
                if isinstance(controller_output, bytes):
                    body = controller_output
                else:
                    body = orjson.dumps(controller_output)
            else:
                body = str(controller_output).encode()

        elif controller_output is None:
            content_length = 0 if has_content_length else None

            if content_type is None and status in RESPONSES_MAP:
                if headers:
                    return (RESPONSES_MAP[status](
                        make_asgi_headers(headers)), )

                return (RESPONSES_MAP[status](headers), )

            if headers:
                return RESPONSES_MAP[content_type](  # type: ignore
                    content_length,
                    headers=make_asgi_headers(headers))

            return RESPONSES_MAP[content_type](content_length)  # type: ignore

        else:
            raise InvalidReturnError(controller_output, controller)

        content_length = len(body) if has_content_length else None

        return (
            RESPONSES_MAP[content_type](  # type: ignore
                content_length, status, make_asgi_headers(headers)),
            body,
        )