Skip to content

Commit

Permalink
chore: updating templates for python sdk
Browse files Browse the repository at this point in the history
  • Loading branch information
emajo authored and fattureincloud-bot committed Feb 28, 2024
1 parent 08d923a commit da31341
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 65 deletions.
30 changes: 22 additions & 8 deletions templates/openapi-generator/python/README.mustache
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
# FattureInCloud Python SDK

[![PyPI](https://img.shields.io/pypi/v/fattureincloud-python-sdk?color=g)](https://pypi.org/project/fattureincloud-python-sdk/) ![unit tests](https://github.com/fattureincloud/fattureincloud-python-sdk/actions/workflows/validate.yaml/badge.svg)

# {{{projectName}}}
{{#appDescriptionWithNewLines}}
{{{.}}}
Expand All @@ -21,23 +17,41 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})

## Requirements.

Python >= 3.7
Python {{{generatorLanguageVersion}}}

## Installation & Usage
### pip install

You can install our python package directly using:
If the python package is hosted on a repository, you can install directly using:

```sh
pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git
```
(you may need to run `pip` with root permission: `sudo pip install git+https://{{gitHost}}/{{{gitUserId}}}/{{{gitRepoId}}}.git`)

Then import the package:
```python
import {{{packageName}}}
```

### Setuptools

Install via [Setuptools](http://pypi.python.org/pypi/setuptools).

```sh
pip install fattureincloud-python-sdk
python setup.py install --user
```
(you may need to run `pip` with root permission: `sudo pip install fattureincloud-python-sdk`)
(or `sudo python setup.py install` to install the package for all users)

Then import the package:
```python
import {{{packageName}}}
```

### Tests

Execute `pytest` to run the tests.

## Getting Started

Please follow the [installation procedure](#installation--usage) and then run the following:
Expand Down
26 changes: 11 additions & 15 deletions templates/openapi-generator/python/api.mustache
Original file line number Diff line number Diff line change
@@ -1,23 +1,16 @@
# coding: utf-8

{{>partial_header}}

import io
import warnings

from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt
from typing import Dict, List, Optional, Tuple, Union, Any

try:
from typing import Annotated
except ImportError:
from typing_extensions import Annotated
from typing import Any, Dict, List, Optional, Tuple, Union
from typing_extensions import Annotated

{{#imports}}
{{import}}
{{/imports}}

from {{packageName}}.api_client import ApiClient
from {{packageName}}.api_client import ApiClient, RequestSerialized
from {{packageName}}.api_response import ApiResponse
from {{packageName}}.rest import RESTResponseType

Expand Down Expand Up @@ -84,7 +77,7 @@ class {{classname}}:
_content_type,
_headers,
_host_index,
) -> Tuple:
) -> RequestSerialized:

{{#servers.0}}
_hosts = [{{#servers}}
Expand All @@ -97,8 +90,11 @@ class {{classname}}:
{{/servers.0}}

_collection_formats: Dict[str, str] = {
{{#allParams}}{{#isArray}}
'{{baseName}}': '{{collectionFormat}}',{{/isArray}}{{/allParams}}
{{#allParams}}
{{#isArray}}
'{{baseName}}': '{{collectionFormat}}',
{{/isArray}}
{{/allParams}}
}

_path_params: Dict[str, str] = {}
Expand Down Expand Up @@ -143,7 +139,7 @@ class {{classname}}:
_query_params.append(('{{baseName}}', {{paramName}}))
{{/isDate}}
{{^isDateTime}}{{^isDate}}
_query_params.append(('{{baseName}}', {{paramName}}{{#isEnumRef}}{{/isEnumRef}}))
_query_params.append(('{{baseName}}', {{paramName}}{{#isEnumRef}}.value{{/isEnumRef}}))
{{/isDate}}{{/isDateTime}}
{{/queryParams}}
# process the header parameters
Expand All @@ -167,7 +163,7 @@ class {{classname}}:
{{#isBinary}}
# convert to byte array if the input is a file name (str)
if isinstance({{paramName}}, str):
with io.open({{paramName}}, "rb") as _fp:
with open({{paramName}}, "rb") as _fp:
_body_params = _fp.read()
else:
_body_params = {{paramName}}
Expand Down
72 changes: 41 additions & 31 deletions templates/openapi-generator/python/model_generic.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,14 @@ import pprint
import re # noqa: F401
import json

{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}}
{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}}
{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}}
{{#vendorExtensions.x-py-other-imports}}
{{{.}}}
{{/vendorExtensions.x-py-other-imports}}
{{#vendorExtensions.x-py-model-imports}}
{{{.}}}
{{/vendorExtensions.x-py-model-imports}}
try:
from typing import Self
except ImportError:
from typing_extensions import Self
from typing import Optional, Set
from typing_extensions import Self

class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}):
"""
Expand Down Expand Up @@ -69,11 +64,11 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{/required}}
{{#isArray}}
for i in value:
if i not in ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}):
if i not in set([{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]):
raise ValueError("each list item must be one of ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})")
{{/isArray}}
{{^isArray}}
if value not in ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}):
if value not in set([{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]):
raise ValueError("must be one of enum values ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})")
{{/isArray}}
return value
Expand All @@ -82,22 +77,23 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}

model_config = {
"populate_by_name": True,
"validate_assignment": True
"validate_assignment": True,
"protected_namespaces": (),
}


{{#hasChildren}}
{{#discriminator}}
# JSON field name that stores the object type
__discriminator_property_name: ClassVar[List[str]] = '{{discriminator.propertyBaseName}}'
__discriminator_property_name: ClassVar[str] = '{{discriminator.propertyBaseName}}'

# discriminator mappings
__discriminator_value_class_map: ClassVar[Dict[str, str]] = {
{{#mappedModels}}'{{{mappingName}}}': '{{{modelName}}}'{{^-last}},{{/-last}}{{/mappedModels}}
}

@classmethod
def get_discriminator_value(cls, obj: Dict) -> str:
def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]:
"""Returns the discriminator value (object type) of the data"""
discriminator_value = obj[cls.__discriminator_property_name]
if discriminator_value:
Expand All @@ -117,7 +113,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
return json.dumps(self.to_dict())

@classmethod
def from_json(cls, json_str: str) -> {{^hasChildren}}Self{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union[{{#children}}Self{{^-last}}, {{/-last}}{{/children}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}{{/hasChildren}}:
def from_json(cls, json_str: str) -> Optional[{{^hasChildren}}Self{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union[{{#children}}Self{{^-last}}, {{/-last}}{{/children}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}{{/hasChildren}}]:
"""Create an instance of {{{classname}}} from a JSON string"""
return cls.from_dict(json.loads(json_str))

Expand All @@ -137,16 +133,18 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
* Fields in `self.additional_properties` are added to the output dict.
{{/isAdditionalPropertiesTrue}}
"""
excluded_fields: Set[str] = set([
{{#vendorExtensions.x-py-readonly}}
"{{{.}}}",
{{/vendorExtensions.x-py-readonly}}
{{#isAdditionalPropertiesTrue}}
"additional_properties",
{{/isAdditionalPropertiesTrue}}
])

_dict = self.model_dump(
by_alias=True,
exclude={
{{#vendorExtensions.x-py-readonly}}
"{{{.}}}",
{{/vendorExtensions.x-py-readonly}}
{{#isAdditionalPropertiesTrue}}
"additional_properties",
{{/isAdditionalPropertiesTrue}}
},
exclude=excluded_fields,
exclude_none=True,
)
{{#allVars}}
Expand Down Expand Up @@ -225,12 +223,21 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
_dict[_key] = _value

{{/isAdditionalPropertiesTrue}}
{{#allVars}}
{{#isNullable}}
# set to None if {{{name}}} (nullable) is None
# and model_fields_set contains the field
if self.{{name}} is None and "{{{name}}}" in self.model_fields_set:
_dict['{{{baseName}}}'] = None

{{/isNullable}}
{{/allVars}}
return _dict

{{#hasChildren}}
@classmethod
def from_dict(cls, obj: Dict) -> {{^hasChildren}}Self{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union[{{#children}}Self{{^-last}}, {{/-last}}{{/children}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}{{/hasChildren}}:
def from_dict(cls, obj: Dict[str, Any]) -> Optional[{{#discriminator}}Union[{{#children}}Self{{^-last}}, {{/-last}}{{/children}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}]:
"""Create an instance of {{{classname}}} from a dict"""
{{#hasChildren}}
{{#discriminator}}
# look up the object type based on discriminator mapping
object_type = cls.get_discriminator_value(obj)
Expand All @@ -242,8 +249,11 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name +
", mapping: " + json.dumps(cls.__discriminator_value_class_map))
{{/discriminator}}
{{/hasChildren}}
{{^hasChildren}}
{{/hasChildren}}
{{^hasChildren}}
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of {{{classname}}} from a dict"""
if obj is None:
return None

Expand All @@ -270,7 +280,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{^items.items.isPrimitiveType}}
"{{{baseName}}}": [
[{{{items.items.dataType}}}.from_dict(_inner_item) for _inner_item in _item]
for _item in obj.get("{{{baseName}}}")
for _item in obj["{{{baseName}}}"]
] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}}
{{/items.items.isPrimitiveType}}
{{/items.isArray}}
Expand All @@ -280,7 +290,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
"{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}}
{{/items.isEnumOrRef}}
{{^items.isEnumOrRef}}
"{{{baseName}}}": [{{{items.dataType}}}.from_dict(_item) for _item in obj.get("{{{baseName}}}")] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}}
"{{{baseName}}}": [{{{items.dataType}}}.from_dict(_item) for _item in obj["{{{baseName}}}"]] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}}
{{/items.isEnumOrRef}}
{{/items.isPrimitiveType}}
{{#items.isPrimitiveType}}
Expand Down Expand Up @@ -313,14 +323,14 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
if _v is not None
else None
)
for _k, _v in obj.get("{{{baseName}}}").items()
for _k, _v in obj.get("{{{baseName}}}", {}).items()
){{^-last}},{{/-last}}
{{/items.isArray}}
{{/items.isContainer}}
{{^items.isContainer}}
"{{{baseName}}}": dict(
(_k, {{{items.dataType}}}.from_dict(_v))
for _k, _v in obj.get("{{{baseName}}}").items()
for _k, _v in obj["{{{baseName}}}"].items()
)
if obj.get("{{{baseName}}}") is not None
else None{{^-last}},{{/-last}}
Expand All @@ -338,7 +348,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{^isContainer}}
{{^isPrimitiveType}}
{{^isEnumOrRef}}
"{{{baseName}}}": {{{dataType}}}.from_dict(obj.get("{{{baseName}}}")) if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}}
"{{{baseName}}}": {{{dataType}}}.from_dict(obj["{{{baseName}}}"]) if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}}
{{/isEnumOrRef}}
{{#isEnumOrRef}}
"{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}}
Expand All @@ -363,7 +373,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}

{{/isAdditionalPropertiesTrue}}
return _obj
{{/hasChildren}}
{{/hasChildren}}

{{#vendorExtensions.x-py-postponed-model-imports.size}}
{{#vendorExtensions.x-py-postponed-model-imports}}
Expand Down
3 changes: 2 additions & 1 deletion templates/openapi-generator/python/requirements.mustache
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
python_dateutil >= 2.5.3
setuptools >= 21.0.0
urllib3 >= 1.26.8, < 2.1.0
urllib3 >= 1.25.3, < 2.1.0
pydantic >= 2
typing-extensions >= 4.7.1
{{#asyncio}}
aiohttp >= 3.0.0
aiohttp-retry >= 2.8.3
{{/asyncio}}
{{#hasHttpSignatureMethods}}
pycryptodome >= 3.9.0
Expand Down
17 changes: 7 additions & 10 deletions templates/openapi-generator/python/setup.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ PYTHON_REQUIRES = ">=3.7"
{{#apis}}
{{#-last}}
REQUIRES = [
"urllib3 >= 1.26.8, < 2.1.0",
"urllib3 >= 1.25.3, < 2.1.0",
"python-dateutil",
{{#asyncio}}
"aiohttp >= 3.0.0",
"aiohttp-retry >= 2.8.3",
{{/asyncio}}
{{#tornado}}
"tornado>=4.2,<5",
Expand All @@ -33,26 +34,22 @@ REQUIRES = [
"typing-extensions >= 4.7.1",
]

def readme():
with open('README.md') as f:
return f.read()

file = readme()

setup(
name=NAME,
version=VERSION,
description="Python SDK for the Fatture in Cloud API",
description="{{appName}}",
author="{{infoName}}{{^infoName}}OpenAPI Generator community{{/infoName}}",
author_email="{{infoEmail}}{{^infoEmail}}team@openapitools.org{{/infoEmail}}",
url="{{packageUrl}}",
keywords=["fattureincloud", "fatture in cloud", "fatture", "fic", "fattureincloud sdk", "fatture in cloud sdk"],
keywords=["OpenAPI", "OpenAPI-Generator", "{{{appName}}}"],
install_requires=REQUIRES,
packages=find_packages(exclude=["test", "tests"]),
include_package_data=True,
{{#licenseInfo}}license="{{.}}",
{{/licenseInfo}}long_description_content_type='text/markdown',
long_description=file, # noqa: E501
long_description="""\
{{appDescription}}
""", # noqa: E501
package_data={"{{{packageName}}}": ["py.typed"]},
)
{{/-last}}
Expand Down

0 comments on commit da31341

Please sign in to comment.