Skip to content
This repository has been archived by the owner on Jan 2, 2025. It is now read-only.

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
artsmolin committed Sep 10, 2023
1 parent c0950fd commit 8c5076a
Show file tree
Hide file tree
Showing 14 changed files with 70 additions and 374 deletions.
30 changes: 2 additions & 28 deletions examples/petstore/client_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,18 +270,6 @@ class DeleteUserPathParams(BaseModel):
username: str = Field(alias="username")


class LoginuserResponse200(BaseModel):
"""
None
"""

model_config = ConfigDict(
populate_by_name=True, # Addressing by field name, even if there is an alias.
)
text: str | None = None


class CreateuserswithlistinputRequestBody(BaseModel):
"""
None
Expand All @@ -304,18 +292,6 @@ class GetinventoryResponse200(BaseModel):
)


class UploadfileRequestBody(BaseModel):
"""
None
"""

model_config = ConfigDict(
populate_by_name=True, # Addressing by field name, even if there is an alias.
)
content: bytes | None = None


class FindpetsbytagsResponse200(BaseModel):
"""
None
Expand Down Expand Up @@ -883,7 +859,7 @@ async def loginUser(
query_params: LoginUserQueryParams | dict[str, Any],
auth: BasicAuth | None = None,
content: str | bytes | None = None,
) -> EmptyBody | LoginuserResponse200:
) -> EmptyBody | str:
method = "get"

path = "/user/login"
Expand Down Expand Up @@ -939,7 +915,7 @@ async def loginUser(
)

if response.status_code == 200:
return LoginuserResponse200(text=response.text)
return response.text

if response.status_code == 400:
if response.content is None:
Expand Down Expand Up @@ -2056,10 +2032,8 @@ def _parse_any_of(self, item: dict[str, Any], schema_classes: list[Any]) -> Any:
raise Exception('Can\'t parse "{item}"')


LoginuserResponse200.model_rebuild()
CreateuserswithlistinputRequestBody.model_rebuild()
GetinventoryResponse200.model_rebuild()
UploadfileRequestBody.model_rebuild()
FindpetsbytagsResponse200.model_rebuild()
FindpetsbystatusResponse200.model_rebuild()
AddpetortagRequestBody.model_rebuild()
Expand Down
30 changes: 2 additions & 28 deletions examples/petstore/client_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,18 +270,6 @@ class DeleteUserPathParams(BaseModel):
username: str = Field(alias="username")


class LoginuserResponse200(BaseModel):
"""
None
"""

model_config = ConfigDict(
populate_by_name=True, # Addressing by field name, even if there is an alias.
)
text: str | None = None


class CreateuserswithlistinputRequestBody(BaseModel):
"""
None
Expand All @@ -304,18 +292,6 @@ class GetinventoryResponse200(BaseModel):
)


class UploadfileRequestBody(BaseModel):
"""
None
"""

model_config = ConfigDict(
populate_by_name=True, # Addressing by field name, even if there is an alias.
)
content: bytes | None = None


class FindpetsbytagsResponse200(BaseModel):
"""
None
Expand Down Expand Up @@ -873,7 +849,7 @@ def loginUser(
query_params: LoginUserQueryParams | dict[str, Any],
auth: BasicAuth | None = None,
content: str | bytes | None = None,
) -> EmptyBody | LoginuserResponse200:
) -> EmptyBody | str:
method = "get"

path = "/user/login"
Expand Down Expand Up @@ -927,7 +903,7 @@ def loginUser(
)

if response.status_code == 200:
return LoginuserResponse200(text=response.text)
return response.text

if response.status_code == 400:
if response.content is None:
Expand Down Expand Up @@ -2032,10 +2008,8 @@ def _parse_any_of(self, item: dict[str, Any], schema_classes: list[Any]) -> Any:
raise Exception('Can\'t parse "{item}"')


LoginuserResponse200.model_rebuild()
CreateuserswithlistinputRequestBody.model_rebuild()
GetinventoryResponse200.model_rebuild()
UploadfileRequestBody.model_rebuild()
FindpetsbytagsResponse200.model_rebuild()
FindpetsbystatusResponse200.model_rebuild()
AddpetortagRequestBody.model_rebuild()
Expand Down
10 changes: 7 additions & 3 deletions pythogen/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,12 @@ class Type(Enum):
object = 'object'
null = 'null'

# TODO: refactor
any_of = 'any_of'
def is_primitive(self) -> bool:
return self in Type.get_primitive_types()

@classmethod
def get_primitive_types(cls) -> tuple[Type, ...]:
return (cls.string, cls.number, cls.integer, cls.boolean, cls.null)


@dataclass
Expand Down Expand Up @@ -314,7 +318,7 @@ def _build_sorted_schemas(self, keys: list[str], exclude_enums: bool = False):

@property
def sorted_schemas(self) -> list[SchemaObject]:
keys = [key for key, schema in self.schemas.items() if schema.enum is None]
keys = [key for key, schema in self.schemas.items() if schema.enum is None and not schema.type.is_primitive()]
return self._build_sorted_schemas(keys, exclude_enums=True)

@property
Expand Down
5 changes: 1 addition & 4 deletions pythogen/parsers/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@
logger = logging.getLogger(__name__)


PRIMITIVE_TYPES = ('string', 'number', 'integer', 'boolean', 'null')


class SchemaParser:
"""Парсер схемы
Expand Down Expand Up @@ -351,7 +348,7 @@ def _parse_items(
else:
items_schema_id = f'<inline+{models.SchemaObject.__name__}>'
schema = self.parse_item(items_schema_id, items_schema_data)
if items_schema_data.get('type') not in PRIMITIVE_TYPES:
if models.Type(items_schema_data.get('type')) not in models.Type.get_primitive_types():
self._inline_schema_aggregator.add(items_schema_id, schema)
return schema

Expand Down
17 changes: 6 additions & 11 deletions pythogen/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,19 +189,16 @@ def iterresponsemap(responses: models.ResponsesObject) -> list[tuple[str, str]]:
continue
continue

if response.schema.type == models.Type.string:
if response.schema.format is models.Format.binary:
mapper = f'{classname(response.schema.id)}(content=response.content)'
mapping.append((code, mapper))
continue
if response.schema.type == models.Type.string and response.schema.format is models.Format.binary:
mapping.append((code, 'response.content'))
continue

mapper = f'{classname(response.schema.id)}(text=response.text)'
mapping.append((code, mapper))
if response.schema.type == models.Type.string:
mapping.append((code, 'response.text'))
continue

if response.schema.type == models.Type.integer:
mapper = f'{classname(response.schema.id)}(text=response.text)'
mapping.append((code, mapper))
mapping.append((code, f'int(response.text)'))
continue

raise NotImplementedError(
Expand All @@ -218,8 +215,6 @@ def j2_responserepr(responses: models.ResponsesObject, document: models.Document
for response in responses.patterned.values():
if not response.schema:
types.append('EmptyBody')
elif response.schema.type in [models.Type.string, models.Type.integer]:
types.append(classname(response.schema.id))
else:
types.append(j2_typerepr(response.schema, document))

Expand Down
2 changes: 1 addition & 1 deletion pythogen/templates/http_client/main.j2
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ class {{ classname(model.id) }}(RootModel):
root: {{ repranyof(model.any_of, document) }}
{%- elif model.all_of %}
class {{ classname(model.id) }}(
{% for all_of_item_model in model.all_of %}{{ classname(all_of_item_model.id) }},{% endfor %}
{% for all_of_item_model in model.all_of %}{{ typerepr(all_of_item_model, document) }},{% endfor %}
):
"""
{{ model.title }}
Expand Down
66 changes: 7 additions & 59 deletions tests/clients/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,42 +304,6 @@ class RequestBodyAnyofRequestBody(RootModel):
root: Data | PostObjectData


class GetBinaryResponse200(BaseModel):
"""
None
"""

model_config = ConfigDict(
populate_by_name=True, # Addressing by field name, even if there is an alias.
)
content: bytes | None = None


class GetTextAsIntegerResponse200(BaseModel):
"""
None
"""

model_config = ConfigDict(
populate_by_name=True, # Addressing by field name, even if there is an alias.
)
text: int | None = None


class GetTextResponse200(BaseModel):
"""
None
"""

model_config = ConfigDict(
populate_by_name=True, # Addressing by field name, even if there is an alias.
)
text: str | None = None


class GetListObjectsResponse200(BaseModel):
"""
None
Expand Down Expand Up @@ -433,18 +397,6 @@ class OptionalAnyofStringDataObj(RootModel):
root: str | None


class OptionalAnyofStringDataObjItem0(BaseModel):
"""
None
"""

model_config = ConfigDict(
populate_by_name=True, # Addressing by field name, even if there is an alias.
)
text: str | None = None


class AnimalObj(RootModel):
"""
None
Expand Down Expand Up @@ -534,7 +486,7 @@ class AnyOfChildItem(RootModel):
"""

root: Dog | Cat
root: Dog | Cat | int


class ListAnyOfResp(BaseModel):
Expand Down Expand Up @@ -1084,7 +1036,7 @@ async def get_text(
self,
auth: BasicAuth | None = None,
content: str | bytes | None = None,
) -> GetTextResponse200 | None:
) -> str | None:
method = "get"

path = "/text"
Expand Down Expand Up @@ -1137,13 +1089,13 @@ async def get_text(
)

if response.status_code == 200:
return GetTextResponse200(text=response.text)
return response.text

async def get_text_as_integer(
self,
auth: BasicAuth | None = None,
content: str | bytes | None = None,
) -> GetTextAsIntegerResponse200 | None:
) -> int | None:
method = "get"

path = "/text_as_integer"
Expand Down Expand Up @@ -1196,7 +1148,7 @@ async def get_text_as_integer(
)

if response.status_code == 200:
return GetTextAsIntegerResponse200(text=response.text)
return int(response.text)

async def get_empty(
self,
Expand Down Expand Up @@ -1332,7 +1284,7 @@ async def get_binary(
self,
auth: BasicAuth | None = None,
content: str | bytes | None = None,
) -> GetBinaryResponse200 | None:
) -> bytes | None:
method = "get"

path = "/binary"
Expand Down Expand Up @@ -1385,7 +1337,7 @@ async def get_binary(
)

if response.status_code == 200:
return GetBinaryResponse200(content=response.content)
return response.content

async def get_allof(
self,
Expand Down Expand Up @@ -2232,9 +2184,6 @@ def _parse_any_of(self, item: dict[str, Any], schema_classes: list[Any]) -> Any:


RequestBodyAnyofRequestBody.model_rebuild()
GetBinaryResponse200.model_rebuild()
GetTextAsIntegerResponse200.model_rebuild()
GetTextResponse200.model_rebuild()
GetListObjectsResponse200.model_rebuild()
RewardsListItem.model_rebuild()
GetObjectWithInlineArrayResponse200.model_rebuild()
Expand All @@ -2243,7 +2192,6 @@ def _parse_any_of(self, item: dict[str, Any], schema_classes: list[Any]) -> Any:
GetObjectNoRefSchemaResponse200.model_rebuild()
IntEnumOrNullObj.model_rebuild()
OptionalAnyofStringDataObj.model_rebuild()
OptionalAnyofStringDataObjItem0.model_rebuild()
AnimalObj.model_rebuild()
AnyOfChildObj.model_rebuild()
TierObj.model_rebuild()
Expand Down
Loading

0 comments on commit 8c5076a

Please sign in to comment.