Skip to content

Commit

Permalink
Merge pull request #61 from andruwwwka/small-fixes
Browse files Browse the repository at this point in the history
Small fixes
  • Loading branch information
andruwwwka authored Aug 27, 2023
2 parents 183d8be + eeaad3c commit fcf4d99
Show file tree
Hide file tree
Showing 14 changed files with 63 additions and 55 deletions.
2 changes: 1 addition & 1 deletion examples/petstore/client_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
#
# Generator info:
# GitHub Page: https://github.com/artsmolin/pythogen
# Version: 0.2.18
# Version: 0.2.19
# ==============================================================================

# jinja2: lstrip_blocks: "True"
Expand Down
2 changes: 1 addition & 1 deletion examples/petstore/client_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
#
# Generator info:
# GitHub Page: https://github.com/artsmolin/pythogen
# Version: 0.2.18
# Version: 0.2.19
# ==============================================================================

# jinja2: lstrip_blocks: "True"
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "pythogen"
version = "0.2.18"
version = "0.2.19"
description = "Generator of python HTTP-clients from OpenApi specification."
homepage = "https://github.com/artsmolin/pythogen"
repository = "https://github.com/artsmolin/pythogen"
Expand Down
70 changes: 38 additions & 32 deletions pythogen/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,33 @@
from enum import Enum


class SafetyKeyMixin:
@property
def key(self):
return self._safe_key()

def _safe_key(self):
if self.safety_key:
return self.safety_key

if self.orig_key.isidentifier() and not keyword.iskeyword(self.orig_key):
return self.orig_key

key = self.orig_key

if not key.isidentifier():
key = re.sub('[-.]', '_', key)
# stolen from https://stackoverflow.com/a/3303361
key = re.sub('[^0-9a-zA-Z_]', '', key)
key = re.sub('^[^a-zA-Z_]+', '', key)

if keyword.iskeyword(key):
key += "_"

self.safety_key = key
return self.safety_key


class HttpMethod(Enum):
get = 'get'
put = 'put'
Expand All @@ -36,11 +63,19 @@ class Format(Enum):
date = 'date'
byte = 'byte'
binary = 'binary'
date_time = 'date-time'
datetime = 'date-time'
password = 'password'
uuid = 'uuid'
uri = 'uri'

@classmethod
def _missing_(cls, value):
value = re.sub('[_-]*', '', value)
for member in cls:
if member.lower() == value:
return member
return None


@dataclass
class ContactObject:
Expand Down Expand Up @@ -91,36 +126,11 @@ class Type(Enum):


@dataclass
class SchemaProperty:
class SchemaProperty(SafetyKeyMixin):
orig_key: str
safety_key: str | None
schema: 'SchemaObject'

@property
def key(self):
return self._safe_key()

def _safe_key(self):
if self.safety_key:
return self.safety_key

if self.orig_key.isidentifier() and not keyword.iskeyword(self.orig_key):
return self.orig_key

key = self.orig_key

if not key.isidentifier():
key = re.sub('[-.]', '_', key)
# stolen from https://stackoverflow.com/a/3303361
key = re.sub('[^0-9a-zA-Z_]', '', key)
key = re.sub('^[^a-zA-Z_]+', '', key)

if keyword.iskeyword(key):
key += "_"

self.safety_key = key
return self.safety_key


@dataclass
class SchemaObject:
Expand Down Expand Up @@ -159,7 +169,7 @@ def optional_properties(self) -> list[SchemaProperty]:


@dataclass
class ParameterObject:
class ParameterObject(SafetyKeyMixin):
"""
https://swagger.io/specification/#parameter-object
"""
Expand All @@ -172,10 +182,6 @@ class ParameterObject:
required: bool
schema: SchemaObject

@property
def key(self):
return self.safety_key if self.safety_key else self.orig_key


@dataclass
class RequestBodyObject:
Expand Down
2 changes: 1 addition & 1 deletion pythogen/parsers/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def __init__(self, ref_resolver: RefResolver, schema_parser: SchemaParser, opena
self._schema_parser = schema_parser

def parse_collections(self) -> dict[str, models.ParameterObject]:
parameters = self._openapi_data["components"].get('parameters', {})
parameters = self._openapi_data.get('components', {}).get('parameters', {})
result = {}
for parameter_id, parameter_data in parameters.items():
if parameter_data.get('$ref', None):
Expand Down
2 changes: 1 addition & 1 deletion pythogen/parsers/request_body.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def _drop_binary_strings(schema_data):
file_required = False
for k in list(schema_data.get("properties", {})):
prop = properties[k]
if prop.get("type") == "string" and prop.get("format") == models.DataFormat.binary.value:
if prop.get("type") == "string" and prop.get("format") == models.Format.binary.value:
del properties[k]
if k in required:
required.remove(k)
Expand Down
17 changes: 9 additions & 8 deletions pythogen/parsers/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,15 @@ def parse_item(self, response_id: str, response_data: dict[str, Any]) -> models.
logger.error(f'Unable to parse response "{response_id}", multiple media types not implemented yet')
media_type = media_types[0]
media_type_data = content[media_type]
schema_data = media_type_data['schema']

if schema_data.get('$ref', None):
resolved_ref = self._ref_resolver.resolve(schema_data['$ref'])
schema = self._schema_parser.parse_item(resolved_ref.ref_id, resolved_ref.ref_data)
else:
schema = self._schema_parser.parse_item(response_id, schema_data)
self._inline_schema_aggregator.add(response_id, schema)
schema_data = media_type_data.get('schema')

if schema_data:
if schema_data.get('$ref', None):
resolved_ref = self._ref_resolver.resolve(schema_data['$ref'])
schema = self._schema_parser.parse_item(resolved_ref.ref_id, resolved_ref.ref_data)
else:
schema = self._schema_parser.parse_item(response_id, schema_data)
self._inline_schema_aggregator.add(response_id, schema)

return models.ResponseObject(
id=response_id,
Expand Down
9 changes: 5 additions & 4 deletions pythogen/parsers/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,11 @@ def __init__(
self._discriminator_base_class_schemas = discriminator_base_class_schemas
self._inline_schema_aggregator = inline_schema_aggregator

self._schema_ids = list(self._openapi_data["components"].get('schemas', {}))
self._processiong_parsed_schema_id_count: dict[str, int] = defaultdict(int)
self._schemas: dict[str, models.SchemaObject] = {}

def parse_collection(self) -> dict[str, models.SchemaObject]:
schemas_data = self._openapi_data["components"].get('schemas', {})
schemas_data = self._openapi_data.get('components', {}).get('schemas', {})
for schema_id, schema_data in schemas_data.items():
if schema_data.get('$ref', None):
resolved_ref = self._ref_resolver.resolve(schema_data['$ref'])
Expand Down Expand Up @@ -142,6 +141,8 @@ def _parse_type(self, data: dict[str, Any]) -> models.Type:
data_type = models.Type.object
elif 'anyOf' in data:
data_type = models.Type.any_of
elif 'type' not in data:
data_type = models.Type.object
else:
raw_data_type: str | None = data.get('type')
try:
Expand All @@ -154,7 +155,7 @@ def _parse_format(self, data: dict[str, Any]) -> models.Format | None:
data_format = data.get('format')
if data_format:
try:
return models.Format[data_format.replace('-', '_')]
return models.Format(data_format)
except Exception:
raise Exception(f'Unable to parse schema "{id}", unknown format "{data_format}"')
return None
Expand Down Expand Up @@ -189,7 +190,7 @@ def _parse_properties(
data_format = data.get('format')
if data_format:
try:
data_format = models.Format[data_format.replace('-', '_')]
data_format = models.Format(data_format)
except Exception:
raise Exception(f'Unable to parse schema "{id}", unknown format "{data_format}"')

Expand Down
2 changes: 1 addition & 1 deletion pythogen/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,5 +322,5 @@ def parameterfield(parameter: models.ParameterObject) -> str:
models.Format.binary: 'bytes',
models.Format.uri: 'HttpUrl',
models.Format.date: 'datetime.date',
models.Format.date_time: 'datetime.datetime',
models.Format.datetime: 'datetime.datetime',
}
2 changes: 1 addition & 1 deletion tests/clients/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
#
# Generator info:
# GitHub Page: https://github.com/artsmolin/pythogen
# Version: 0.2.18
# Version: 0.2.19
# ==============================================================================

# jinja2: lstrip_blocks: "True"
Expand Down
2 changes: 1 addition & 1 deletion tests/clients/async_client_with_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
#
# Generator info:
# GitHub Page: https://github.com/artsmolin/pythogen
# Version: 0.2.18
# Version: 0.2.19
# ==============================================================================

# jinja2: lstrip_blocks: "True"
Expand Down
2 changes: 1 addition & 1 deletion tests/clients/async_client_with_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
#
# Generator info:
# GitHub Page: https://github.com/artsmolin/pythogen
# Version: 0.2.18
# Version: 0.2.19
# ==============================================================================

# jinja2: lstrip_blocks: "True"
Expand Down
2 changes: 1 addition & 1 deletion tests/clients/sync_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
#
# Generator info:
# GitHub Page: https://github.com/artsmolin/pythogen
# Version: 0.2.18
# Version: 0.2.19
# ==============================================================================

# jinja2: lstrip_blocks: "True"
Expand Down
2 changes: 1 addition & 1 deletion tests/clients/sync_client_with_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
#
# Generator info:
# GitHub Page: https://github.com/artsmolin/pythogen
# Version: 0.2.18
# Version: 0.2.19
# ==============================================================================

# jinja2: lstrip_blocks: "True"
Expand Down

0 comments on commit fcf4d99

Please sign in to comment.