Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat python type hints #749

Open
wants to merge 2 commits into
base: feat-python-type-hints
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions templates/python/base/requests/api.twig
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
return self.client.call('{{ method.method | caseLower }}', path, {
return self.client.call('{{ method.method | caseLower }}', path=api_path, headers={
{% for parameter in method.parameters.header %}
'{{ parameter.name }}': {{ parameter.name | escapeKeyword | caseSnake }},
{% endfor %}
{% for key, header in method.headers %}
'{{ key }}': '{{ header }}',
{% endfor %}
}, params)
}, params=params)
4 changes: 2 additions & 2 deletions templates/python/base/requests/file.twig
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
{% endif %}
{% endfor %}

return self.client.chunked_upload(path, {
return self.client.chunked_upload(path=api_path, headers={
{% for parameter in method.parameters.header %}
'{{ parameter.name }}': {{ parameter.name | escapeKeyword | caseSnake }},
{% endfor %}
{% for key, header in method.headers %}
'{{ key }}': '{{ header }}',
{% endfor %}
}, params, param_name, on_progress, upload_id)
}, params=params, param_name=param_name, on_progress=on_progress, upload_id=upload_id)
53 changes: 25 additions & 28 deletions templates/python/package/client.py.twig
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
from __future__ import annotations
import io
import requests
import os
from .input_file import InputFile
from .exception import {{spec.title | caseUcfirst}}Exception
from typing import Optional

class Client:
def __init__(self):
self._chunk_size = 5*1024*1024
self._self_signed = False
self._endpoint = '{{spec.endpoint}}'
self._global_headers = {
def __init__(self) -> None:
self._chunk_size: int = 5*1024*1024
self._self_signed: bool = False
self._endpoint: str = '{{spec.endpoint}}'
self._global_headers: dict[str, str] = {
'content-type': '',
'user-agent' : '{{spec.title | caseUcfirst}}{{ language.name | caseUcfirst }}SDK/{{ sdk.version }} (${os.uname().sysname}; ${os.uname().version}; ${os.uname().machine})',
'x-sdk-name': '{{ sdk.name }}',
Expand All @@ -21,20 +22,20 @@ class Client:
{% endfor %}
}

def set_self_signed(self, status: bool = True):
def set_self_signed(self, status: bool = True) -> 'Client':
self._self_signed = status
return self

def set_endpoint(self, endpoint: str):
def set_endpoint(self, endpoint: str) -> 'Client':
self._endpoint = endpoint
return self

def add_header(self, key: str, value: str):
def add_header(self, key: str, value: str) -> 'Client':
self._global_headers[key.lower()] = value
return self
{% for header in spec.global.headers %}

def set_{{header.key | caseSnake}}(self, value: str):
def set_{{header.key | caseSnake}}(self, value: str) -> 'Client':
{% if header.description %}
"""{{header.description}}"""

Expand All @@ -43,17 +44,13 @@ class Client:
return self
{% endfor %}

def call(self, method: str, path: str = '', headers: Optional[dict] = None, params: Optional[dict] = None):
if headers is None:
headers = {}
def call(self, method: str, path: str = '', headers: dict[str, str] = {}, params: dict[str, Any] = {}) -> dict[str, Any] | bytes:
params = {k: v for k, v in params.items() if v is not None} # Remove None values from params dictionary

if params is None:
params = {}

data = {}
json = {}
files = {}
stringify = False
data: dict[str, Any] = {}
json: dict[str, Any] = {}
files: dict[str, Any] = {}
stringify: bool = False

headers = {**self._global_headers, **headers}

Expand Down Expand Up @@ -106,12 +103,12 @@ class Client:
def chunked_upload(
self,
path: str,
headers: Optional[dict] = None,
params: Optional[dict] = None,
headers: dict[str, str] = {},
params: dict[str, Any] = {},
param_name: str = '',
on_progress = None,
on_progress: Any = None,
upload_id: str = ''
):
) -> dict[str, Any]:
input_file = params[param_name]

if input_file.source_type == 'path':
Expand Down Expand Up @@ -158,7 +155,7 @@ class Client:
input_file.data = input[offset:end]

params[param_name] = input_file
headers["content-range"] = f'bytes {offset}-{min((offset + self._chunk_size) - 1, size)}/{size}'
headers["content-range"] = f'bytes {offset}-{min((offset + self._chunk_size) - 1, size - 1)}/{size}'

result = self.call(
'post',
Expand All @@ -173,7 +170,7 @@ class Client:
headers["x-{{ spec.title | caseLower }}-id"] = result["$id"]

if on_progress is not None:
end = min((((counter * self._chunk_size) + self._chunk_size) - 1), size)
end = min((((counter * self._chunk_size) + self._chunk_size) - 1), size - 1)
on_progress({
"$id": result["$id"],
"progress": min(offset, size)/size * 100,
Expand All @@ -186,8 +183,8 @@ class Client:

return result

def flatten(self, data: dict, prefix: str = '', stringify: bool = False):
output = {}
def flatten(self, data: Union[dict[str, Any], list], prefix: str = '', stringify: bool = False) -> dict[str, Any]:
output: dict[str, Any] = {}
i = 0

for key in data:
Expand Down
13 changes: 7 additions & 6 deletions templates/python/package/exception.py.twig
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from typing import Optional
from __future__ import annotations
from typing import Any

class {{spec.title | caseUcfirst}}Exception(Exception):
def __init__(self, message: str, code: int = 0, type: Optional[str] = None, response: Optional[dict] = None):
self.message = message
self.code = code
self.type = type
self.response = response
def __init__(self, message: str, code: int = 0, type: str | None = None, response: Any | None = None) -> None:
self.message: str = message
self.code: int = code
self.type: str | None = type
self.response: Any | None = response
super().__init__(self.message)
6 changes: 3 additions & 3 deletions templates/python/package/id.py.twig
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
class ID:
@staticmethod
def custom(id):
def custom(id: str) -> str:
return id

@staticmethod
def unique():
return 'unique()'
def unique() -> str:
return 'unique()'
24 changes: 12 additions & 12 deletions templates/python/package/input_file.py.twig
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
from __future__ import annotations
import os
import mimetypes
from typing import Optional

class InputFile:
@classmethod
def from_path(cls, path: str) -> 'InputFile':
instance = cls()
instance.path = path
instance.filename = os.path.basename(path)
instance.mime_type = mimetypes.guess_type(path)
instance.source_type = 'path'
instance: 'InputFile' = cls()
instance.path: str = path
instance.filename: str = os.path.basename(path)
instance.mime_type: str | None = mimetypes.guess_type(path)[0]
instance.source_type: str = 'path'
return instance

@classmethod
def from_bytes(cls, bytes, filename: Optional[str] = None, mime_type: Optional[str] = None) -> 'InputFile':
instance = cls()
instance.data = bytes
instance.filename = filename
instance.mime_type = mime_type
instance.source_type = 'bytes'
def from_bytes(cls, bytes: bytes, filename: str | None = None, mime_type: str | None = None) -> 'InputFile':
instance: 'InputFile' = cls()
instance.data: bytes = bytes
instance.filename: str | None = filename
instance.mime_type: str | None = mime_type
instance.source_type: str = 'bytes'
return instance
10 changes: 5 additions & 5 deletions templates/python/package/permission.py.twig
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
class Permission:

@staticmethod
def read(role) -> str:
def read(role: str) -> str:
return f'read("{role}")'

@staticmethod
def write(role) -> str:
def write(role: str) -> str:
return f'write("{role}")'

@staticmethod
def create(role) -> str:
def create(role: str) -> str:
return f'create("{role}")'

@staticmethod
def update(role) -> str:
def update(role: str) -> str:
return f'update("{role}")'

@staticmethod
def delete(role) -> str:
def delete(role: str) -> str:
return f'delete("{role}")'
54 changes: 28 additions & 26 deletions templates/python/package/query.py.twig
Original file line number Diff line number Diff line change
@@ -1,92 +1,94 @@
from __future__ import annotations

class Query:
@staticmethod
def equal(attribute, value) -> str:
def equal(attribute: str, value: str | list[str]) -> str:
return Query.add_query(attribute, "equal", value)

@staticmethod
def not_equal(attribute, value) -> str:
def not_equal(attribute: str, value: str | list[str]) -> str:
return Query.add_query(attribute, "notEqual", value)

@staticmethod
def less_than(attribute, value) -> str:
def less_than(attribute: str, value: str | list[str]) -> str:
return Query.add_query(attribute, "lessThan", value)

@staticmethod
def less_than_equal(attribute, value) -> str:
def less_than_equal(attribute: str, value: str | list[str]) -> str:
return Query.add_query(attribute, "lessThanEqual", value)

@staticmethod
def greater_than(attribute, value) -> str:
def greater_than(attribute: str, value: str | list[str]) -> str:
return Query.add_query(attribute, "greaterThan", value)

@staticmethod
def greater_than_equal(attribute, value) -> str:
def greater_than_equal(attribute: str, value: str | list[str]) -> str:
return Query.add_query(attribute, "greaterThanEqual", value)

@staticmethod
def is_null(attribute) -> str:
def is_null(attribute: str) -> str:
return f'isNull("{attribute}")'

@staticmethod
def is_not_null(attribute) -> str:
def is_not_null(attribute: str) -> str:
return f'isNotNull("{attribute}")'

@staticmethod
def between(attribute, start, end) -> str:
return Query.add_query(attribute, "between", [start, end])
def between(attribute: str, start: str | int, end: str | int) -> str:
return f'between("{attribute}", {Query.parseValues(start)}, {Query.parseValues(end)})'

@staticmethod
def starts_with(attribute, value) -> str:
def starts_with(attribute: str, value: str) -> str:
return Query.add_query(attribute, "startsWith", value)

@staticmethod
def ends_with(attribute, value) -> str:
def ends_with(attribute: str, value: str) -> str:
return Query.add_query(attribute, "endsWith", value)

@staticmethod
def select(attributes) -> str:
def select(attributes: list[str]) -> str:
return f'select([{",".join(map(Query.parseValues, attributes))}])'

@staticmethod
def search(attribute, value) -> str:
def search(attribute: str, value: str) -> str:
return Query.add_query(attribute, "search", value)

@staticmethod
def order_asc(attribute) -> str:
def order_asc(attribute: str) -> str:
return f'orderAsc("{attribute}")'

@staticmethod
def order_desc(attribute) -> str:
def order_desc(attribute: str) -> str:
return f'orderDesc("{attribute}")'

@staticmethod
def cursor_before(id) -> str:
def cursor_before(id: str) -> str:
return f'cursorBefore("{id}")'

@staticmethod
def cursor_after(id) -> str:
def cursor_after(id: str) -> str:
return f'cursorAfter("{id}")'

@staticmethod
def limit(limit) -> str:
def limit(limit: int) -> str:
return f'limit({limit})'

@staticmethod
def offset(offset) -> str:
def offset(offset: int) -> str:
return f'offset({offset})'

@staticmethod
def add_query(attribute, method, value) -> str:
if type(value) == list:
def add_query(attribute: str, method: str, value: str | list[str]) -> str:
if isinstance(value, list):
return f'{method}("{attribute}", [{",".join(map(Query.parseValues, value))}])'
else:
return f'{method}("{attribute}", [{Query.parseValues(value)}])'

@staticmethod
def parseValues(value) -> str:
if type(value) == str:
def parseValues(value: str | int | bool) -> str:
if isinstance(value, str):
return f'"{value}"'
elif type(value) == bool:
elif isinstance(value, bool):
return str(value).lower()
else:
return str(value)
return str(value)
Loading