Skip to content

Commit

Permalink
Merge pull request #60 from fingerprintjs/INTER-803-inline-types
Browse files Browse the repository at this point in the history
Use inline types instead of type annotations
  • Loading branch information
ilfa authored Aug 1, 2024
2 parents 4eefbd6 + f6c8b47 commit 89d18e3
Show file tree
Hide file tree
Showing 104 changed files with 1,169 additions and 1,789 deletions.
6 changes: 2 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ api_instance = fingerprint_pro_server_api_sdk.FingerprintApi(configuration)
Fetching visits using visitorId:
```python
import fingerprint_pro_server_api_sdk
from fingerprint_pro_server_api_sdk import Response
from fingerprint_pro_server_api_sdk.rest import ApiException, KnownApiException

configuration = fingerprint_pro_server_api_sdk.Configuration(api_key="SECRET_API_KEY")
Expand All @@ -102,7 +101,7 @@ limit = 10 # int | Limit scanned results. For performance reasons, the API fi
#pagination_key = 'pagination_key_example' # str | Use `paginationKey` to get the next page of results. When more results are available (e.g., you requested 200 results using `limit` parameter, but a total of 600 results are available), the `paginationKey` top-level attribute is added to the response. The key corresponds to the `requestId` of the last returned event. In the following request, use that value in the `paginationKey` parameter to get the next page of results: 1. First request, returning most recent 200 events: `GET api-base-url/visitors/:visitorId?limit=200` 2. Use `response.paginationKey` to get the next page of results: `GET api-base-url/visitors/:visitorId?limit=200&paginationKey=1683900801733.Ogvu1j` Pagination happens during scanning and before filtering, so you can get less visits than the `limit` you specified with more available on the next page. When there are no more results available for scanning, the `paginationKey` attribute is not returned. (optional)

try:
api_response: Response = api_instance.get_visits(visitor_id, limit=2)
api_response = api_instance.get_visits(visitor_id, limit=2)
print(api_response)
except KnownApiException as e:
structured_error = e.structured_error
Expand Down Expand Up @@ -133,7 +132,6 @@ except ApiException as e:
Fetching events for requestId:
```python
import fingerprint_pro_server_api_sdk
from fingerprint_pro_server_api_sdk import EventResponse
from fingerprint_pro_server_api_sdk.rest import ApiException, KnownApiException

configuration = fingerprint_pro_server_api_sdk.Configuration(api_key="SECRET_API_KEY")
Expand All @@ -142,7 +140,7 @@ api_instance = fingerprint_pro_server_api_sdk.FingerprintApi(configuration)
request_id = 'request_id_example' # str | The unique event [identifier](https://dev.fingerprint.com/docs/js-agent#requestid).

try:
events_response: EventResponse = api_instance.get_event(request_id)
events_response = api_instance.get_event(request_id)

except KnownApiException as e:
structured_error = e.structured_error
Expand Down
137 changes: 77 additions & 60 deletions fingerprint_pro_server_api_sdk/api/fingerprint_api.py

Large diffs are not rendered by default.

146 changes: 51 additions & 95 deletions fingerprint_pro_server_api_sdk/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,25 @@
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import datetime
import json
import mimetypes
import os
import re
import tempfile

from urllib.parse import quote
from multiprocessing import Pool
from typing import Optional, Any, Union, Dict, List, Tuple
from datetime import date, datetime

from fingerprint_pro_server_api_sdk.configuration import Configuration
import fingerprint_pro_server_api_sdk.models
from fingerprint_pro_server_api_sdk import rest
from fingerprint_pro_server_api_sdk.rest import ApiException
from fingerprint_pro_server_api_sdk.rest import ApiException, RESTResponse
from fingerprint_pro_server_api_sdk.base_model import BaseModel


class ApiClient(object):
class ApiClient:
"""Generic API client for Swagger client library builds.
Swagger generic API client. This client handles the client-
Expand All @@ -50,13 +53,13 @@ class ApiClient(object):
'float': float,
'str': str,
'bool': bool,
'date': datetime.date,
'datetime': datetime.datetime,
'date': date,
'datetime': datetime,
'object': object,
}

def __init__(self, configuration=None, header_name=None, header_value=None,
cookie=None, pool=None):
def __init__(self, configuration: Optional[Configuration] = None, header_name: Optional[str] = None,
header_value: Optional[str] = None, cookie: Optional[str] = None, pool: Optional[Pool] = None):
if configuration is None:
configuration = Configuration()
self.configuration = configuration
Expand All @@ -83,23 +86,25 @@ def __del__(self):
self.pool.join()

@property
def user_agent(self):
def user_agent(self) -> Optional[str]:
"""User agent for this API client"""
return self.default_headers['User-Agent']

@user_agent.setter
def user_agent(self, value):
def user_agent(self, value: str):
self.default_headers['User-Agent'] = value

def set_default_header(self, header_name, header_value):
def set_default_header(self, header_name: str, header_value: str):
self.default_headers[header_name] = header_value

def __call_api(
self, resource_path, method, path_params=None,
query_params=None, header_params=None, body=None, post_params=None,
files=None, response_type=None, auth_settings=None,
_return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None):
self, resource_path: str, method: str, path_params: Optional[Dict[str, Any]] = None,
query_params: Optional[List[Tuple[str, Any]]] = None, header_params: Optional[Dict[str, Any]] = None,
body: Any = None, post_params: Optional[List[Tuple[str, Any]]] = None,
files: Optional[Dict[str, Any]] = None, response_type: Optional[str] = None,
auth_settings: Optional[List[str]] = None, _return_http_data_only: Optional[bool] = None,
collection_formats: Optional[Dict[str, Any]] = None, _preload_content: bool = True,
_request_timeout: Optional[int] = None):

config = self.configuration

Expand Down Expand Up @@ -176,7 +181,7 @@ def __call_api(
return (return_data, response_data.status,
response_data.getheaders())

def sanitize_for_serialization(self, obj):
def sanitize_for_serialization(self, obj: Union[Dict[str, Any], List[Tuple[str, Any]], BaseModel]):
"""Builds a JSON POST object.
If obj is None, return None.
Expand All @@ -200,7 +205,7 @@ def sanitize_for_serialization(self, obj):
elif isinstance(obj, tuple):
return tuple(self.sanitize_for_serialization(sub_obj)
for sub_obj in obj)
elif isinstance(obj, (datetime.datetime, datetime.date)):
elif isinstance(obj, (datetime, date)):
return obj.isoformat()

if isinstance(obj, dict):
Expand All @@ -218,7 +223,7 @@ def sanitize_for_serialization(self, obj):
return {key: self.sanitize_for_serialization(val)
for key, val in obj_dict.items()}

def deserialize(self, response, response_type, is_error=False):
def deserialize(self, response: Union[RESTResponse, ApiException], response_type: Any, is_error=False):
"""Deserializes response into an object.
:param response: RESTResponse object to be deserialized.
Expand Down Expand Up @@ -248,7 +253,7 @@ def deserialize(self, response, response_type, is_error=False):

return self.__deserialize(data, response_type)

def __deserialize(self, data, klass):
def __deserialize(self, data: Union[Dict, List, str], klass: Any):
"""Deserializes dict, list, str into an object.
:param data: dict, list or str.
Expand Down Expand Up @@ -279,20 +284,21 @@ def __deserialize(self, data, klass):
if klass in self.PRIMITIVE_TYPES:
return self.__deserialize_primitive(data, klass)
elif klass == object:
return self.__deserialize_object(data)
elif klass == datetime.date:
return data
elif klass == date:
return self.__deserialize_date(data)
elif klass == datetime.datetime:
elif klass == datetime:
return self.__deserialize_datatime(data)
else:
return self.__deserialize_model(data, klass)

def call_api(self, resource_path, method,
path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None,
response_type=None, auth_settings=None, async_req=None,
_return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None):
def call_api(self, resource_path: str, method: str, path_params: Optional[Dict[str, Any]] = None,
query_params: Optional[List[Tuple[str, Any]]] = None, header_params: Optional[Dict[str, Any]] = None,
body: Any = None, post_params: Optional[List[Tuple[str, Any]]] = None,
files: Optional[Dict[str, Any]] = None, response_type: Optional[str] = None,
auth_settings: Optional[List[str]] = None, async_req: Optional[bool] = None,
_return_http_data_only: Optional[bool] = None, collection_formats: Optional[Dict[str, Any]] = None,
_preload_content: bool = True, _request_timeout: Optional[int] = None):
"""Makes the HTTP request (synchronous) and returns deserialized data.
To make an async request, set the async_req parameter.
Expand All @@ -304,13 +310,13 @@ def call_api(self, resource_path, method,
:param header_params: Header parameters to be
placed in the request header.
:param body: Request body.
:param post_params dict: Request post form parameters,
:param post_params: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param auth_settings list: Auth Settings names for the request.
:param response: Response data type.
:param files dict: key -> filename, value -> filepath,
:param auth_settings: Auth Settings names for the request.
:param response_type: Response data type.
:param files: key -> filename, value -> filepath,
for `multipart/form-data`.
:param async_req bool: execute request asynchronously
:param async_req: execute request asynchronously
:param _return_http_data_only: response data without head status code
and headers
:param collection_formats: dict of collection formats for path, query,
Expand Down Expand Up @@ -351,57 +357,14 @@ def request(self, method, url, query_params=None, headers=None,
post_params=None, body=None, _preload_content=True,
_request_timeout=None):
"""Makes the HTTP request using RESTClient."""
if method == "GET":
return self.rest_client.GET(url,
query_params=query_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
headers=headers)
elif method == "HEAD":
return self.rest_client.HEAD(url,
query_params=query_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
headers=headers)
elif method == "OPTIONS":
return self.rest_client.OPTIONS(url,
if method in ["GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE"]:
return self.rest_client.request(method, url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "POST":
return self.rest_client.POST(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "PUT":
return self.rest_client.PUT(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "PATCH":
return self.rest_client.PATCH(url,
query_params=query_params,
headers=headers,
post_params=post_params,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
elif method == "DELETE":
return self.rest_client.DELETE(url,
query_params=query_params,
headers=headers,
_preload_content=_preload_content,
_request_timeout=_request_timeout,
body=body)
else:
raise ValueError(
"http method must be `GET`, `HEAD`, `OPTIONS`,"
Expand Down Expand Up @@ -438,7 +401,8 @@ def parameters_to_tuples(self, params, collection_formats):
new_params.append((k, v))
return new_params

def prepare_post_parameters(self, post_params=None, files=None):
def prepare_post_parameters(self, post_params: Optional[List[Tuple[str, Any]]] = None,
files: Optional[Dict[str, Any]] = None):
"""Builds form parameters.
:param post_params: Normal form parameters.
Expand Down Expand Up @@ -466,7 +430,7 @@ def prepare_post_parameters(self, post_params=None, files=None):

return params

def select_header_accept(self, accepts):
def select_header_accept(self, accepts: List[str]) -> Optional[str]:
"""Returns `Accept` based on an array of accepts provided.
:param accepts: List of headers.
Expand All @@ -482,7 +446,7 @@ def select_header_accept(self, accepts):
else:
return ', '.join(accepts)

def select_header_content_type(self, content_types):
def select_header_content_type(self, content_types: List[str]) -> str:
"""Returns `Content-Type` based on an array of content_types provided.
:param content_types: List of content-types.
Expand All @@ -498,11 +462,12 @@ def select_header_content_type(self, content_types):
else:
return content_types[0]

def update_params_for_auth(self, headers, querys, auth_settings):
def update_params_for_auth(self, headers: Optional[Dict[str, Any]], queries: Optional[List[Tuple[str, Any]]],
auth_settings: Optional[List[str]]):
"""Updates header and query params based on authentication setting.
:param headers: Header parameters dict to be updated.
:param querys: Query parameters tuple list to be updated.
:param queries: Query parameters tuple list to be updated.
:param auth_settings: Authentication setting identifiers list.
"""
if not auth_settings:
Expand All @@ -516,7 +481,7 @@ def update_params_for_auth(self, headers, querys, auth_settings):
elif auth_setting['in'] == 'header':
headers[auth_setting['key']] = auth_setting['value']
elif auth_setting['in'] == 'query':
querys.append((auth_setting['key'], auth_setting['value']))
queries.append((auth_setting['key'], auth_setting['value']))
else:
raise ValueError(
'Authentication token must be in `query` or `header`'
Expand Down Expand Up @@ -565,18 +530,10 @@ def __deserialize_primitive(self, data, klass):
except TypeError:
return data

def __deserialize_object(self, value):
"""Return a original value.
:return: object.
"""
return value

def __deserialize_date(self, string):
def __deserialize_date(self, string: str) -> date:
"""Deserializes string to date.
:param string: str.
:return: date.
"""
try:
from dateutil.parser import parse
Expand All @@ -589,13 +546,12 @@ def __deserialize_date(self, string):
reason="Failed to parse `{0}` as date object".format(string)
)

def __deserialize_datatime(self, string):
def __deserialize_datatime(self, string: str) -> datetime:
"""Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
from dateutil.parser import parse
Expand Down
Loading

0 comments on commit 89d18e3

Please sign in to comment.