templatefox 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ """API response object."""
2
+
3
+ from __future__ import annotations
4
+ from typing import Optional, Generic, Mapping, TypeVar
5
+ from pydantic import Field, StrictInt, StrictBytes, BaseModel
6
+
7
+ T = TypeVar("T")
8
+
9
+ class ApiResponse(BaseModel, Generic[T]):
10
+ """
11
+ API response object
12
+ """
13
+
14
+ status_code: StrictInt = Field(description="HTTP status code")
15
+ headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers")
16
+ data: T = Field(description="Deserialized data given the data type")
17
+ raw_data: StrictBytes = Field(description="Raw data (HTTP response body)")
18
+
19
+ model_config = {
20
+ "arbitrary_types_allowed": True
21
+ }
@@ -0,0 +1,609 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ TemplateFox API
5
+
6
+ Generate PDFs from HTML templates via API. Design once, generate thousands.
7
+
8
+ The version of the OpenAPI document: 1.0.0
9
+ Contact: support@pdftemplateapi.com
10
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
11
+
12
+ Do not edit the class manually.
13
+ """ # noqa: E501
14
+
15
+
16
+ import copy
17
+ import http.client as httplib
18
+ import logging
19
+ from logging import FileHandler
20
+ import multiprocessing
21
+ import sys
22
+ from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict, Union
23
+ from typing_extensions import NotRequired, Self
24
+
25
+ import urllib3
26
+
27
+
28
+ JSON_SCHEMA_VALIDATION_KEYWORDS = {
29
+ 'multipleOf', 'maximum', 'exclusiveMaximum',
30
+ 'minimum', 'exclusiveMinimum', 'maxLength',
31
+ 'minLength', 'pattern', 'maxItems', 'minItems'
32
+ }
33
+
34
+ ServerVariablesT = Dict[str, str]
35
+
36
+ GenericAuthSetting = TypedDict(
37
+ "GenericAuthSetting",
38
+ {
39
+ "type": str,
40
+ "in": str,
41
+ "key": str,
42
+ "value": str,
43
+ },
44
+ )
45
+
46
+
47
+ OAuth2AuthSetting = TypedDict(
48
+ "OAuth2AuthSetting",
49
+ {
50
+ "type": Literal["oauth2"],
51
+ "in": Literal["header"],
52
+ "key": Literal["Authorization"],
53
+ "value": str,
54
+ },
55
+ )
56
+
57
+
58
+ APIKeyAuthSetting = TypedDict(
59
+ "APIKeyAuthSetting",
60
+ {
61
+ "type": Literal["api_key"],
62
+ "in": str,
63
+ "key": str,
64
+ "value": Optional[str],
65
+ },
66
+ )
67
+
68
+
69
+ BasicAuthSetting = TypedDict(
70
+ "BasicAuthSetting",
71
+ {
72
+ "type": Literal["basic"],
73
+ "in": Literal["header"],
74
+ "key": Literal["Authorization"],
75
+ "value": Optional[str],
76
+ },
77
+ )
78
+
79
+
80
+ BearerFormatAuthSetting = TypedDict(
81
+ "BearerFormatAuthSetting",
82
+ {
83
+ "type": Literal["bearer"],
84
+ "in": Literal["header"],
85
+ "format": Literal["JWT"],
86
+ "key": Literal["Authorization"],
87
+ "value": str,
88
+ },
89
+ )
90
+
91
+
92
+ BearerAuthSetting = TypedDict(
93
+ "BearerAuthSetting",
94
+ {
95
+ "type": Literal["bearer"],
96
+ "in": Literal["header"],
97
+ "key": Literal["Authorization"],
98
+ "value": str,
99
+ },
100
+ )
101
+
102
+
103
+ HTTPSignatureAuthSetting = TypedDict(
104
+ "HTTPSignatureAuthSetting",
105
+ {
106
+ "type": Literal["http-signature"],
107
+ "in": Literal["header"],
108
+ "key": Literal["Authorization"],
109
+ "value": None,
110
+ },
111
+ )
112
+
113
+
114
+ AuthSettings = TypedDict(
115
+ "AuthSettings",
116
+ {
117
+ "ApiKeyAuth": APIKeyAuthSetting,
118
+ },
119
+ total=False,
120
+ )
121
+
122
+
123
+ class HostSettingVariable(TypedDict):
124
+ description: str
125
+ default_value: str
126
+ enum_values: List[str]
127
+
128
+
129
+ class HostSetting(TypedDict):
130
+ url: str
131
+ description: str
132
+ variables: NotRequired[Dict[str, HostSettingVariable]]
133
+
134
+
135
+ class Configuration:
136
+ """This class contains various settings of the API client.
137
+
138
+ :param host: Base url.
139
+ :param ignore_operation_servers
140
+ Boolean to ignore operation servers for the API client.
141
+ Config will use `host` as the base url regardless of the operation servers.
142
+ :param api_key: Dict to store API key(s).
143
+ Each entry in the dict specifies an API key.
144
+ The dict key is the name of the security scheme in the OAS specification.
145
+ The dict value is the API key secret.
146
+ :param api_key_prefix: Dict to store API prefix (e.g. Bearer).
147
+ The dict key is the name of the security scheme in the OAS specification.
148
+ The dict value is an API key prefix when generating the auth data.
149
+ :param username: Username for HTTP basic authentication.
150
+ :param password: Password for HTTP basic authentication.
151
+ :param access_token: Access token.
152
+ :param server_index: Index to servers configuration.
153
+ :param server_variables: Mapping with string values to replace variables in
154
+ templated server configuration. The validation of enums is performed for
155
+ variables with defined enum values before.
156
+ :param server_operation_index: Mapping from operation ID to an index to server
157
+ configuration.
158
+ :param server_operation_variables: Mapping from operation ID to a mapping with
159
+ string values to replace variables in templated server configuration.
160
+ The validation of enums is performed for variables with defined enum
161
+ values before.
162
+ :param ssl_ca_cert: str - the path to a file of concatenated CA certificates
163
+ in PEM format.
164
+ :param retries: Number of retries for API requests.
165
+ :param ca_cert_data: verify the peer using concatenated CA certificate data
166
+ in PEM (str) or DER (bytes) format.
167
+ :param cert_file: the path to a client certificate file, for mTLS.
168
+ :param key_file: the path to a client key file, for mTLS.
169
+
170
+ :Example:
171
+
172
+ API Key Authentication Example.
173
+ Given the following security scheme in the OpenAPI specification:
174
+ components:
175
+ securitySchemes:
176
+ cookieAuth: # name for the security scheme
177
+ type: apiKey
178
+ in: cookie
179
+ name: JSESSIONID # cookie name
180
+
181
+ You can programmatically set the cookie:
182
+
183
+ conf = templatefox.Configuration(
184
+ api_key={'cookieAuth': 'abc123'}
185
+ api_key_prefix={'cookieAuth': 'JSESSIONID'}
186
+ )
187
+
188
+ The following cookie will be added to the HTTP request:
189
+ Cookie: JSESSIONID abc123
190
+ """
191
+
192
+ _default: ClassVar[Optional[Self]] = None
193
+
194
+ def __init__(
195
+ self,
196
+ host: Optional[str]=None,
197
+ api_key: Optional[Dict[str, str]]=None,
198
+ api_key_prefix: Optional[Dict[str, str]]=None,
199
+ username: Optional[str]=None,
200
+ password: Optional[str]=None,
201
+ access_token: Optional[str]=None,
202
+ server_index: Optional[int]=None,
203
+ server_variables: Optional[ServerVariablesT]=None,
204
+ server_operation_index: Optional[Dict[int, int]]=None,
205
+ server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None,
206
+ ignore_operation_servers: bool=False,
207
+ ssl_ca_cert: Optional[str]=None,
208
+ retries: Optional[int] = None,
209
+ ca_cert_data: Optional[Union[str, bytes]] = None,
210
+ cert_file: Optional[str]=None,
211
+ key_file: Optional[str]=None,
212
+ *,
213
+ debug: Optional[bool] = None,
214
+ ) -> None:
215
+ """Constructor
216
+ """
217
+ self._base_path = "https://api.pdftemplateapi.com" if host is None else host
218
+ """Default Base url
219
+ """
220
+ self.server_index = 0 if server_index is None and host is None else server_index
221
+ self.server_operation_index = server_operation_index or {}
222
+ """Default server index
223
+ """
224
+ self.server_variables = server_variables or {}
225
+ self.server_operation_variables = server_operation_variables or {}
226
+ """Default server variables
227
+ """
228
+ self.ignore_operation_servers = ignore_operation_servers
229
+ """Ignore operation servers
230
+ """
231
+ self.temp_folder_path = None
232
+ """Temp file folder for downloading files
233
+ """
234
+ # Authentication Settings
235
+ self.api_key = {}
236
+ if api_key:
237
+ self.api_key = api_key
238
+ """dict to store API key(s)
239
+ """
240
+ self.api_key_prefix = {}
241
+ if api_key_prefix:
242
+ self.api_key_prefix = api_key_prefix
243
+ """dict to store API prefix (e.g. Bearer)
244
+ """
245
+ self.refresh_api_key_hook = None
246
+ """function hook to refresh API key if expired
247
+ """
248
+ self.username = username
249
+ """Username for HTTP basic authentication
250
+ """
251
+ self.password = password
252
+ """Password for HTTP basic authentication
253
+ """
254
+ self.access_token = access_token
255
+ """Access token
256
+ """
257
+ self.logger = {}
258
+ """Logging Settings
259
+ """
260
+ self.logger["package_logger"] = logging.getLogger("templatefox")
261
+ self.logger["urllib3_logger"] = logging.getLogger("urllib3")
262
+ self.logger_format = '%(asctime)s %(levelname)s %(message)s'
263
+ """Log format
264
+ """
265
+ self.logger_stream_handler = None
266
+ """Log stream handler
267
+ """
268
+ self.logger_file_handler: Optional[FileHandler] = None
269
+ """Log file handler
270
+ """
271
+ self.logger_file = None
272
+ """Debug file location
273
+ """
274
+ if debug is not None:
275
+ self.debug = debug
276
+ else:
277
+ self.__debug = False
278
+ """Debug switch
279
+ """
280
+
281
+ self.verify_ssl = True
282
+ """SSL/TLS verification
283
+ Set this to false to skip verifying SSL certificate when calling API
284
+ from https server.
285
+ """
286
+ self.ssl_ca_cert = ssl_ca_cert
287
+ """Set this to customize the certificate file to verify the peer.
288
+ """
289
+ self.ca_cert_data = ca_cert_data
290
+ """Set this to verify the peer using PEM (str) or DER (bytes)
291
+ certificate data.
292
+ """
293
+ self.cert_file = cert_file
294
+ """client certificate file
295
+ """
296
+ self.key_file = key_file
297
+ """client key file
298
+ """
299
+ self.assert_hostname = None
300
+ """Set this to True/False to enable/disable SSL hostname verification.
301
+ """
302
+ self.tls_server_name = None
303
+ """SSL/TLS Server Name Indication (SNI)
304
+ Set this to the SNI value expected by the server.
305
+ """
306
+
307
+ self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
308
+ """urllib3 connection pool's maximum number of connections saved
309
+ per pool. urllib3 uses 1 connection as default value, but this is
310
+ not the best value when you are making a lot of possibly parallel
311
+ requests to the same host, which is often the case here.
312
+ cpu_count * 5 is used as default value to increase performance.
313
+ """
314
+
315
+ self.proxy: Optional[str] = None
316
+ """Proxy URL
317
+ """
318
+ self.proxy_headers = None
319
+ """Proxy headers
320
+ """
321
+ self.safe_chars_for_path_param = ''
322
+ """Safe chars for path_param
323
+ """
324
+ self.retries = retries
325
+ """Adding retries to override urllib3 default value 3
326
+ """
327
+ # Enable client side validation
328
+ self.client_side_validation = True
329
+
330
+ self.socket_options = None
331
+ """Options to pass down to the underlying urllib3 socket
332
+ """
333
+
334
+ self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
335
+ """datetime format
336
+ """
337
+
338
+ self.date_format = "%Y-%m-%d"
339
+ """date format
340
+ """
341
+
342
+ def __deepcopy__(self, memo: Dict[int, Any]) -> Self:
343
+ cls = self.__class__
344
+ result = cls.__new__(cls)
345
+ memo[id(self)] = result
346
+ for k, v in self.__dict__.items():
347
+ if k not in ('logger', 'logger_file_handler'):
348
+ setattr(result, k, copy.deepcopy(v, memo))
349
+ # shallow copy of loggers
350
+ result.logger = copy.copy(self.logger)
351
+ # use setters to configure loggers
352
+ result.logger_file = self.logger_file
353
+ result.debug = self.debug
354
+ return result
355
+
356
+ def __setattr__(self, name: str, value: Any) -> None:
357
+ object.__setattr__(self, name, value)
358
+
359
+ @classmethod
360
+ def set_default(cls, default: Optional[Self]) -> None:
361
+ """Set default instance of configuration.
362
+
363
+ It stores default configuration, which can be
364
+ returned by get_default_copy method.
365
+
366
+ :param default: object of Configuration
367
+ """
368
+ cls._default = default
369
+
370
+ @classmethod
371
+ def get_default_copy(cls) -> Self:
372
+ """Deprecated. Please use `get_default` instead.
373
+
374
+ Deprecated. Please use `get_default` instead.
375
+
376
+ :return: The configuration object.
377
+ """
378
+ return cls.get_default()
379
+
380
+ @classmethod
381
+ def get_default(cls) -> Self:
382
+ """Return the default configuration.
383
+
384
+ This method returns newly created, based on default constructor,
385
+ object of Configuration class or returns a copy of default
386
+ configuration.
387
+
388
+ :return: The configuration object.
389
+ """
390
+ if cls._default is None:
391
+ cls._default = cls()
392
+ return cls._default
393
+
394
+ @property
395
+ def logger_file(self) -> Optional[str]:
396
+ """The logger file.
397
+
398
+ If the logger_file is None, then add stream handler and remove file
399
+ handler. Otherwise, add file handler and remove stream handler.
400
+
401
+ :param value: The logger_file path.
402
+ :type: str
403
+ """
404
+ return self.__logger_file
405
+
406
+ @logger_file.setter
407
+ def logger_file(self, value: Optional[str]) -> None:
408
+ """The logger file.
409
+
410
+ If the logger_file is None, then add stream handler and remove file
411
+ handler. Otherwise, add file handler and remove stream handler.
412
+
413
+ :param value: The logger_file path.
414
+ :type: str
415
+ """
416
+ self.__logger_file = value
417
+ if self.__logger_file:
418
+ # If set logging file,
419
+ # then add file handler and remove stream handler.
420
+ self.logger_file_handler = logging.FileHandler(self.__logger_file)
421
+ self.logger_file_handler.setFormatter(self.logger_formatter)
422
+ for _, logger in self.logger.items():
423
+ logger.addHandler(self.logger_file_handler)
424
+
425
+ @property
426
+ def debug(self) -> bool:
427
+ """Debug status
428
+
429
+ :param value: The debug status, True or False.
430
+ :type: bool
431
+ """
432
+ return self.__debug
433
+
434
+ @debug.setter
435
+ def debug(self, value: bool) -> None:
436
+ """Debug status
437
+
438
+ :param value: The debug status, True or False.
439
+ :type: bool
440
+ """
441
+ self.__debug = value
442
+ if self.__debug:
443
+ # if debug status is True, turn on debug logging
444
+ for _, logger in self.logger.items():
445
+ logger.setLevel(logging.DEBUG)
446
+ # turn on httplib debug
447
+ httplib.HTTPConnection.debuglevel = 1
448
+ else:
449
+ # if debug status is False, turn off debug logging,
450
+ # setting log level to default `logging.WARNING`
451
+ for _, logger in self.logger.items():
452
+ logger.setLevel(logging.WARNING)
453
+ # turn off httplib debug
454
+ httplib.HTTPConnection.debuglevel = 0
455
+
456
+ @property
457
+ def logger_format(self) -> str:
458
+ """The logger format.
459
+
460
+ The logger_formatter will be updated when sets logger_format.
461
+
462
+ :param value: The format string.
463
+ :type: str
464
+ """
465
+ return self.__logger_format
466
+
467
+ @logger_format.setter
468
+ def logger_format(self, value: str) -> None:
469
+ """The logger format.
470
+
471
+ The logger_formatter will be updated when sets logger_format.
472
+
473
+ :param value: The format string.
474
+ :type: str
475
+ """
476
+ self.__logger_format = value
477
+ self.logger_formatter = logging.Formatter(self.__logger_format)
478
+
479
+ def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]:
480
+ """Gets API key (with prefix if set).
481
+
482
+ :param identifier: The identifier of apiKey.
483
+ :param alias: The alternative identifier of apiKey.
484
+ :return: The token for api key authentication.
485
+ """
486
+ if self.refresh_api_key_hook is not None:
487
+ self.refresh_api_key_hook(self)
488
+ key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
489
+ if key:
490
+ prefix = self.api_key_prefix.get(identifier)
491
+ if prefix:
492
+ return "%s %s" % (prefix, key)
493
+ else:
494
+ return key
495
+
496
+ return None
497
+
498
+ def get_basic_auth_token(self) -> Optional[str]:
499
+ """Gets HTTP basic authentication header (string).
500
+
501
+ :return: The token for basic HTTP authentication.
502
+ """
503
+ username = ""
504
+ if self.username is not None:
505
+ username = self.username
506
+ password = ""
507
+ if self.password is not None:
508
+ password = self.password
509
+
510
+ return urllib3.util.make_headers(
511
+ basic_auth=username + ':' + password
512
+ ).get('authorization')
513
+
514
+ def auth_settings(self)-> AuthSettings:
515
+ """Gets Auth Settings dict for api client.
516
+
517
+ :return: The Auth Settings information dict.
518
+ """
519
+ auth: AuthSettings = {}
520
+ if 'ApiKeyAuth' in self.api_key:
521
+ auth['ApiKeyAuth'] = {
522
+ 'type': 'api_key',
523
+ 'in': 'header',
524
+ 'key': 'x-api-key',
525
+ 'value': self.get_api_key_with_prefix(
526
+ 'ApiKeyAuth',
527
+ ),
528
+ }
529
+ return auth
530
+
531
+ def to_debug_report(self) -> str:
532
+ """Gets the essential information for debugging.
533
+
534
+ :return: The report for debugging.
535
+ """
536
+ return "Python SDK Debug Report:\n"\
537
+ "OS: {env}\n"\
538
+ "Python Version: {pyversion}\n"\
539
+ "Version of the API: 1.0.0\n"\
540
+ "SDK Package Version: 1.0.0".\
541
+ format(env=sys.platform, pyversion=sys.version)
542
+
543
+ def get_host_settings(self) -> List[HostSetting]:
544
+ """Gets an array of host settings
545
+
546
+ :return: An array of host settings
547
+ """
548
+ return [
549
+ {
550
+ 'url': "https://api.pdftemplateapi.com",
551
+ 'description': "Production",
552
+ }
553
+ ]
554
+
555
+ def get_host_from_settings(
556
+ self,
557
+ index: Optional[int],
558
+ variables: Optional[ServerVariablesT]=None,
559
+ servers: Optional[List[HostSetting]]=None,
560
+ ) -> str:
561
+ """Gets host URL based on the index and variables
562
+ :param index: array index of the host settings
563
+ :param variables: hash of variable and the corresponding value
564
+ :param servers: an array of host settings or None
565
+ :return: URL based on host settings
566
+ """
567
+ if index is None:
568
+ return self._base_path
569
+
570
+ variables = {} if variables is None else variables
571
+ servers = self.get_host_settings() if servers is None else servers
572
+
573
+ try:
574
+ server = servers[index]
575
+ except IndexError:
576
+ raise ValueError(
577
+ "Invalid index {0} when selecting the host settings. "
578
+ "Must be less than {1}".format(index, len(servers)))
579
+
580
+ url = server['url']
581
+
582
+ # go through variables and replace placeholders
583
+ for variable_name, variable in server.get('variables', {}).items():
584
+ used_value = variables.get(
585
+ variable_name, variable['default_value'])
586
+
587
+ if 'enum_values' in variable \
588
+ and variable['enum_values'] \
589
+ and used_value not in variable['enum_values']:
590
+ raise ValueError(
591
+ "The variable `{0}` in the host URL has invalid value "
592
+ "{1}. Must be {2}.".format(
593
+ variable_name, variables[variable_name],
594
+ variable['enum_values']))
595
+
596
+ url = url.replace("{" + variable_name + "}", used_value)
597
+
598
+ return url
599
+
600
+ @property
601
+ def host(self) -> str:
602
+ """Return generated host."""
603
+ return self.get_host_from_settings(self.server_index, variables=self.server_variables)
604
+
605
+ @host.setter
606
+ def host(self, value: str) -> None:
607
+ """Fix base path."""
608
+ self._base_path = value
609
+ self.server_index = None