|
1 | 1 | import dataclasses as dc |
2 | 2 | import inspect |
| 3 | +from collections.abc import Sequence |
| 4 | +from typing import Union |
3 | 5 |
|
4 | 6 | import httpx |
| 7 | +import pydantic.fields |
5 | 8 | import typing_extensions as typing |
6 | 9 |
|
7 | | -from ..response import find_type, parse_model |
| 10 | +from ..response import find_type |
8 | 11 | from .params import ParameterAnnotation, RequestPartHandler, find_annotations, process_params |
9 | | -from .response_map import ResponseMap, Responses |
| 12 | +from .response import DefaultEnvelope, PropertyAnnotation, ResponseEnvelope, ResponseMap, ResponsePartHandler, Responses |
10 | 13 |
|
11 | 14 | if typing.TYPE_CHECKING: |
12 | 15 | from .request import RequestBuilder |
@@ -43,20 +46,43 @@ def handle_response(self, response: httpx.Response) -> typing.Any: |
43 | 46 | if typ is None: |
44 | 47 | return None |
45 | 48 |
|
46 | | - obj: typing.Any = parse_model(response, typ) |
47 | | - |
48 | | - if isinstance(obj, Exception): |
49 | | - raise obj |
| 49 | + fields = {} |
| 50 | + for field_name, field_info in typ.model_fields.items(): |
| 51 | + field_info: pydantic.fields.FieldInfo |
| 52 | + handlers: Sequence[Union[ResponsePartHandler, type[ResponsePartHandler]]] = [ |
| 53 | + anno |
| 54 | + for anno in field_info.metadata |
| 55 | + if isinstance(anno, ResponsePartHandler) or (inspect.isclass(anno) and issubclass(anno, ResponsePartHandler)) |
| 56 | + ] |
| 57 | + assert len(handlers) == 1 |
| 58 | + handler = handlers[0] |
| 59 | + if inspect.isclass(handler): |
| 60 | + handler = handler() |
| 61 | + if isinstance(handler, PropertyAnnotation): |
| 62 | + handler.supply_formal(field_name, field_info.annotation) |
| 63 | + handler.apply(fields, response) |
| 64 | + obj = typ.parse_obj(fields) |
| 65 | + # obj: typing.Any = parse_model(response, typ) |
| 66 | + |
| 67 | + if isinstance(obj, DefaultEnvelope): |
| 68 | + if isinstance(obj.body, Exception): |
| 69 | + raise obj.body |
| 70 | + return obj.body |
50 | 71 | else: |
51 | 72 | return obj |
52 | 73 |
|
53 | 74 |
|
54 | 75 | def get_response_map(return_anno: type) -> ResponseMap: |
55 | | - annos = find_annotations(return_anno, Responses) |
| 76 | + annos: typing.Sequence[Responses] = find_annotations(return_anno, Responses) |
56 | 77 | if len(annos) != 1: |
57 | 78 | raise TypeError('Operation function must have exactly one Responses annotation') |
58 | 79 |
|
59 | | - return annos[0].responses |
| 80 | + responses = annos[0].responses |
| 81 | + for media_type_map in responses.values(): |
| 82 | + for media_type, typ in media_type_map.items(): |
| 83 | + if not issubclass(typ, ResponseEnvelope): |
| 84 | + media_type_map[media_type] = DefaultEnvelope[typ] |
| 85 | + return responses |
60 | 86 |
|
61 | 87 |
|
62 | 88 | def get_operation_model( |
|
0 commit comments