This repository was archived by the owner on Dec 25, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathapi_client.handlebars
More file actions
1444 lines (1303 loc) · 55.9 KB
/
api_client.handlebars
File metadata and controls
1444 lines (1303 loc) · 55.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
{{>partial_header}}
import datetime
import dataclasses
import decimal
import enum
import email
import json
import os
import io
import atexit
from multiprocessing import pool
import re
import tempfile
import typing
import typing_extensions
from urllib import parse
import urllib3
from urllib3 import _collections, fields
{{#if tornado}}
import tornado.gen
{{/if}}
import frozendict
from {{packageName}} import exceptions, rest, schemas
from {{packageName}} import configuration as configuration_module
class RequestField(fields.RequestField):
def __eq__(self, other):
if not isinstance(other, RequestField):
return False
return self.__dict__ == other.__dict__
class JSONEncoder(json.JSONEncoder):
compact_separators = (',', ':')
def default(self, obj):
if isinstance(obj, str):
return str(obj)
elif isinstance(obj, float):
return float(obj)
elif isinstance(obj, int):
return int(obj)
elif isinstance(obj, decimal.Decimal):
if obj.as_tuple().exponent >= 0:
return int(obj)
return float(obj)
elif isinstance(obj, schemas.NoneClass):
return None
elif isinstance(obj, schemas.BoolClass):
return bool(obj)
elif isinstance(obj, (dict, frozendict.frozendict)):
return {key: self.default(val) for key, val in obj.items()}
elif isinstance(obj, (list, tuple)):
return [self.default(item) for item in obj]
raise exceptions.ApiValueError('Unable to prepare type {} for serialization'.format(obj.__class__.__name__))
class ParameterInType(enum.Enum):
QUERY = 'query'
HEADER = 'header'
PATH = 'path'
COOKIE = 'cookie'
class ParameterStyle(enum.Enum):
MATRIX = 'matrix'
LABEL = 'label'
FORM = 'form'
SIMPLE = 'simple'
SPACE_DELIMITED = 'spaceDelimited'
PIPE_DELIMITED = 'pipeDelimited'
DEEP_OBJECT = 'deepObject'
class PrefixSeparatorIterator:
# A class to store prefixes and separators for rfc6570 expansions
def __init__(self, prefix: str, separator: str):
self.prefix = prefix
self.separator = separator
self.first = True
if separator in {'.', '|', '%20'}:
item_separator = separator
else:
item_separator = ','
self.item_separator = item_separator
def __iter__(self):
return self
def __next__(self):
if self.first:
self.first = False
return self.prefix
return self.separator
class ParameterSerializerBase:
@staticmethod
def __ref6570_item_value(in_data: typing.Any, percent_encode: bool):
"""
Get representation if str/float/int/None/items in list/ values in dict
None is returned if an item is undefined, use cases are value=
- None
- []
- {}
- [None, None None]
- {'a': None, 'b': None}
"""
if type(in_data) in {str, float, int}:
if percent_encode:
return parse.quote(str(in_data))
return str(in_data)
elif isinstance(in_data, schemas.none_type):
# ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1
return None
elif isinstance(in_data, list) and not in_data:
# ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1
return None
elif isinstance(in_data, dict) and not in_data:
# ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1
return None
raise exceptions.ApiValueError('Unable to generate a ref6570 item representation of {}'.format(in_data))
@staticmethod
def _to_dict(name: str, value: str):
return {name: value}
@classmethod
def __ref6570_str_float_int_expansion(
cls,
variable_name: str,
in_data: typing.Any,
explode: bool,
percent_encode: bool,
prefix_separator_iterator: PrefixSeparatorIterator,
var_name_piece: str,
named_parameter_expansion: bool
) -> str:
item_value = cls.__ref6570_item_value(in_data, percent_encode)
if item_value is None or (item_value == '' and prefix_separator_iterator.separator == ';'):
return next(prefix_separator_iterator) + var_name_piece
value_pair_equals = '=' if named_parameter_expansion else ''
return next(prefix_separator_iterator) + var_name_piece + value_pair_equals + item_value
@classmethod
def __ref6570_list_expansion(
cls,
variable_name: str,
in_data: typing.Any,
explode: bool,
percent_encode: bool,
prefix_separator_iterator: PrefixSeparatorIterator,
var_name_piece: str,
named_parameter_expansion: bool
) -> str:
item_values = [cls.__ref6570_item_value(v, percent_encode) for v in in_data]
item_values = [v for v in item_values if v is not None]
if not item_values:
# ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1
return ""
value_pair_equals = '=' if named_parameter_expansion else ''
if not explode:
return (
next(prefix_separator_iterator) +
var_name_piece +
value_pair_equals +
prefix_separator_iterator.item_separator.join(item_values)
)
# exploded
return next(prefix_separator_iterator) + next(prefix_separator_iterator).join(
[var_name_piece + value_pair_equals + val for val in item_values]
)
@classmethod
def __ref6570_dict_expansion(
cls,
variable_name: str,
in_data: typing.Any,
explode: bool,
percent_encode: bool,
prefix_separator_iterator: PrefixSeparatorIterator,
var_name_piece: str,
named_parameter_expansion: bool
) -> str:
in_data_transformed = {key: cls.__ref6570_item_value(val, percent_encode) for key, val in in_data.items()}
in_data_transformed = {key: val for key, val in in_data_transformed.items() if val is not None}
if not in_data_transformed:
# ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1
return ""
value_pair_equals = '=' if named_parameter_expansion else ''
if not explode:
return (
next(prefix_separator_iterator) +
var_name_piece + value_pair_equals +
prefix_separator_iterator.item_separator.join(
prefix_separator_iterator.item_separator.join(
item_pair
) for item_pair in in_data_transformed.items()
)
)
# exploded
return next(prefix_separator_iterator) + next(prefix_separator_iterator).join(
[key + '=' + val for key, val in in_data_transformed.items()]
)
@classmethod
def _ref6570_expansion(
cls,
variable_name: str,
in_data: typing.Any,
explode: bool,
percent_encode: bool,
prefix_separator_iterator: PrefixSeparatorIterator
) -> str:
"""
Separator is for separate variables like dict with explode true, not for array item separation
"""
named_parameter_expansion = prefix_separator_iterator.separator in {'&', ';'}
var_name_piece = variable_name if named_parameter_expansion else ''
if type(in_data) in {str, float, int}:
return cls.__ref6570_str_float_int_expansion(
variable_name,
in_data,
explode,
percent_encode,
prefix_separator_iterator,
var_name_piece,
named_parameter_expansion
)
elif isinstance(in_data, schemas.none_type):
# ignored by the expansion process https://datatracker.ietf.org/doc/html/rfc6570#section-3.2.1
return ""
elif isinstance(in_data, list):
return cls.__ref6570_list_expansion(
variable_name,
in_data,
explode,
percent_encode,
prefix_separator_iterator,
var_name_piece,
named_parameter_expansion
)
elif isinstance(in_data, dict):
return cls.__ref6570_dict_expansion(
variable_name,
in_data,
explode,
percent_encode,
prefix_separator_iterator,
var_name_piece,
named_parameter_expansion
)
# bool, bytes, etc
raise exceptions.ApiValueError('Unable to generate a ref6570 representation of {}'.format(in_data))
class StyleFormSerializer(ParameterSerializerBase):
@classmethod
def _serialize_form(
cls,
in_data: typing.Union[None, int, float, str, bool, dict, list],
name: str,
explode: bool,
percent_encode: bool,
prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None
) -> str:
if prefix_separator_iterator is None:
prefix_separator_iterator = PrefixSeparatorIterator('', '&')
return cls._ref6570_expansion(
variable_name=name,
in_data=in_data,
explode=explode,
percent_encode=percent_encode,
prefix_separator_iterator=prefix_separator_iterator
)
class StyleSimpleSerializer(ParameterSerializerBase):
@classmethod
def _serialize_simple(
cls,
in_data: typing.Union[None, int, float, str, bool, dict, list],
name: str,
explode: bool,
percent_encode: bool
) -> str:
prefix_separator_iterator = PrefixSeparatorIterator('', ',')
return cls._ref6570_expansion(
variable_name=name,
in_data=in_data,
explode=explode,
percent_encode=percent_encode,
prefix_separator_iterator=prefix_separator_iterator
)
@classmethod
def _deserialize_simple(
cls,
in_data: str,
name: str,
explode: bool,
percent_encode: bool
) -> typing.Union[str, typing.List[str], typing.Dict[str, str]]:
raise NotImplementedError(
"Deserialization of style=simple has not yet been added. "
"If you need this how about you submit a PR adding it?"
)
class JSONDetector:
"""
Works for:
application/json
application/json; charset=UTF-8
application/json-patch+json
application/geo+json
"""
__json_content_type_pattern = re.compile("application/[^+]*[+]?(json);?.*")
@classmethod
def _content_type_is_json(cls, content_type: str) -> bool:
if cls.__json_content_type_pattern.match(content_type):
return True
return False
@dataclasses.dataclass
class ParameterBase(JSONDetector):
in_type: ParameterInType
required: bool
style: typing.Optional[ParameterStyle]
explode: typing.Optional[bool]
allow_reserved: typing.Optional[bool]
schema: typing.Optional[typing.Type[schemas.Schema]]
content: typing.Optional[typing.Dict[str, typing.Type[schemas.Schema]]]
_json_encoder = JSONEncoder()
def __init_subclass__(cls, **kwargs):
if cls.explode is None:
if cls.style is ParameterStyle.FORM:
cls.explode = True
else:
cls.explode = False
@classmethod
def _serialize_json(
cls,
in_data: typing.Union[None, int, float, str, bool, dict, list],
eliminate_whitespace: bool = False
) -> str:
if eliminate_whitespace:
return json.dumps(in_data, separators=cls._json_encoder.compact_separators)
return json.dumps(in_data)
class PathParameter(ParameterBase, StyleSimpleSerializer):
name: str
required: bool = False
in_type: ParameterInType = ParameterInType.PATH
style: ParameterStyle = ParameterStyle.SIMPLE
explode: bool = False
allow_reserved: typing.Optional[bool] = None
schema: typing.Optional[typing.Type[schemas.Schema]] = None
content: typing.Optional[typing.Dict[str, typing.Type[schemas.Schema]]] = None
@classmethod
def __serialize_label(
cls,
in_data: typing.Union[None, int, float, str, bool, dict, list]
) -> typing.Dict[str, str]:
prefix_separator_iterator = PrefixSeparatorIterator('.', '.')
value = cls._ref6570_expansion(
variable_name=cls.name,
in_data=in_data,
explode=cls.explode,
percent_encode=True,
prefix_separator_iterator=prefix_separator_iterator
)
return cls._to_dict(cls.name, value)
@classmethod
def __serialize_matrix(
cls,
in_data: typing.Union[None, int, float, str, bool, dict, list]
) -> typing.Dict[str, str]:
prefix_separator_iterator = PrefixSeparatorIterator(';', ';')
value = cls._ref6570_expansion(
variable_name=cls.name,
in_data=in_data,
explode=cls.explode,
percent_encode=True,
prefix_separator_iterator=prefix_separator_iterator
)
return cls._to_dict(cls.name, value)
@classmethod
def __serialize_simple(
cls,
in_data: typing.Union[None, int, float, str, bool, dict, list],
) -> typing.Dict[str, str]:
value = cls._serialize_simple(
in_data=in_data,
name=cls.name,
explode=cls.explode,
percent_encode=True
)
return cls._to_dict(cls.name, value)
@classmethod
def serialize(
cls,
in_data: typing.Union[
schemas.Schema, decimal.Decimal, int, float, str, datetime.date, datetime.datetime, None, bool, list, tuple, dict, frozendict.frozendict]
) -> typing.Dict[str, str]:
if cls.schema:
cast_in_data = cls.schema(in_data)
cast_in_data = cls._json_encoder.default(cast_in_data)
"""
simple -> path
path:
returns path_params: dict
label -> path
returns path_params
matrix -> path
returns path_params
"""
if cls.style:
if cls.style is ParameterStyle.SIMPLE:
return cls.__serialize_simple(cast_in_data)
elif cls.style is ParameterStyle.LABEL:
return cls.__serialize_label(cast_in_data)
elif cls.style is ParameterStyle.MATRIX:
return cls.__serialize_matrix(cast_in_data)
# cls.content will be length one
for content_type, schema in cls.content.items():
cast_in_data = schema(in_data)
cast_in_data = cls._json_encoder.default(cast_in_data)
if cls._content_type_is_json(content_type):
value = cls._serialize_json(cast_in_data)
return cls._to_dict(cls.name, value)
raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type))
class QueryParameter(ParameterBase, StyleFormSerializer):
name: str
required: bool = False
in_type: ParameterInType = ParameterInType.QUERY
style: ParameterStyle = ParameterStyle.FORM
explode: typing.Optional[bool] = None
allow_reserved: typing.Optional[bool] = None
schema: typing.Optional[typing.Type[schemas.Schema]] = None
content: typing.Optional[typing.Dict[str, typing.Type[schemas.Schema]]] = None
@classmethod
def __serialize_space_delimited(
cls,
in_data: typing.Union[None, int, float, str, bool, dict, list],
prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator]
) -> typing.Dict[str, str]:
if prefix_separator_iterator is None:
prefix_separator_iterator = cls.get_prefix_separator_iterator()
value = cls._ref6570_expansion(
variable_name=cls.name,
in_data=in_data,
explode=cls.explode,
percent_encode=True,
prefix_separator_iterator=prefix_separator_iterator
)
return cls._to_dict(cls.name, value)
@classmethod
def __serialize_pipe_delimited(
cls,
in_data: typing.Union[None, int, float, str, bool, dict, list],
prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator]
) -> typing.Dict[str, str]:
if prefix_separator_iterator is None:
prefix_separator_iterator = cls.get_prefix_separator_iterator()
value = cls._ref6570_expansion(
variable_name=cls.name,
in_data=in_data,
explode=cls.explode,
percent_encode=True,
prefix_separator_iterator=prefix_separator_iterator
)
return cls._to_dict(cls.name, value)
@classmethod
def __serialize_form(
cls,
in_data: typing.Union[None, int, float, str, bool, dict, list],
prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator]
) -> typing.Dict[str, str]:
if prefix_separator_iterator is None:
prefix_separator_iterator = cls.get_prefix_separator_iterator()
value = cls._serialize_form(
in_data,
name=cls.name,
explode=cls.explode,
percent_encode=True,
prefix_separator_iterator=prefix_separator_iterator
)
return cls._to_dict(cls.name, value)
@classmethod
def get_prefix_separator_iterator(cls) -> typing.Optional[PrefixSeparatorIterator]:
if cls.style is ParameterStyle.FORM:
return PrefixSeparatorIterator('?', '&')
elif cls.style is ParameterStyle.SPACE_DELIMITED:
return PrefixSeparatorIterator('', '%20')
elif cls.style is ParameterStyle.PIPE_DELIMITED:
return PrefixSeparatorIterator('', '|')
@classmethod
def serialize(
cls,
in_data: typing.Union[
schemas.Schema, decimal.Decimal, int, float, str, datetime.date, datetime.datetime, None, bool, list, tuple, dict, frozendict.frozendict],
prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None
) -> typing.Dict[str, str]:
if cls.schema:
cast_in_data = cls.schema(in_data)
cast_in_data = cls._json_encoder.default(cast_in_data)
"""
form -> query
query:
- GET/HEAD/DELETE: could use fields
- PUT/POST: must use urlencode to send parameters
returns fields: tuple
spaceDelimited -> query
returns fields
pipeDelimited -> query
returns fields
deepObject -> query, https://github.com/OAI/OpenAPI-Specification/issues/1706
returns fields
"""
if cls.style:
# TODO update query ones to omit setting values when [] {} or None is input
if cls.style is ParameterStyle.FORM:
return cls.__serialize_form(cast_in_data, prefix_separator_iterator)
elif cls.style is ParameterStyle.SPACE_DELIMITED:
return cls.__serialize_space_delimited(cast_in_data, prefix_separator_iterator)
elif cls.style is ParameterStyle.PIPE_DELIMITED:
return cls.__serialize_pipe_delimited(cast_in_data, prefix_separator_iterator)
# cls.content will be length one
if prefix_separator_iterator is None:
prefix_separator_iterator = cls.get_prefix_separator_iterator()
for content_type, schema in cls.content.items():
cast_in_data = schema(in_data)
cast_in_data = cls._json_encoder.default(cast_in_data)
if cls._content_type_is_json(content_type):
value = cls._serialize_json(cast_in_data, eliminate_whitespace=True)
return cls._to_dict(
cls.name,
next(prefix_separator_iterator) + cls.name + '=' + parse.quote(value)
)
raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type))
class CookieParameter(ParameterBase, StyleFormSerializer):
name: str
required: bool = False
style: ParameterStyle = ParameterStyle.FORM
in_type: ParameterInType = ParameterInType.COOKIE
explode: typing.Optional[bool] = None
allow_reserved: typing.Optional[bool] = None
schema: typing.Optional[typing.Type[schemas.Schema]] = None
content: typing.Optional[typing.Dict[str, typing.Type[schemas.Schema]]] = None
@classmethod
def serialize(
cls,
in_data: typing.Union[
schemas.Schema, decimal.Decimal, int, float, str, datetime.date, datetime.datetime, None, bool, list, tuple, dict, frozendict.frozendict]
) -> typing.Dict[str, str]:
if cls.schema:
cast_in_data = cls.schema(in_data)
cast_in_data = cls._json_encoder.default(cast_in_data)
"""
form -> cookie
returns fields: tuple
"""
if cls.style:
"""
TODO add escaping of comma, space, equals
or turn encoding on
"""
value = cls._serialize_form(
cast_in_data,
explode=cls.explode,
name=cls.name,
percent_encode=False,
prefix_separator_iterator=PrefixSeparatorIterator('', '&')
)
return cls._to_dict(cls.name, value)
# cls.content will be length one
for content_type, schema in cls.content.items():
cast_in_data = schema(in_data)
cast_in_data = cls._json_encoder.default(cast_in_data)
if cls._content_type_is_json(content_type):
value = cls._serialize_json(cast_in_data)
return cls._to_dict(cls.name, value)
raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type))
class HeaderParameterWithoutName(ParameterBase, StyleSimpleSerializer):
required: bool = False
style: ParameterStyle = ParameterStyle.SIMPLE
in_type: ParameterInType = ParameterInType.HEADER
explode: bool = False
allow_reserved: typing.Optional[bool] = None
schema: typing.Optional[typing.Type[schemas.Schema]] = None
content: typing.Optional[typing.Dict[str, typing.Type[schemas.Schema]]] = None
@staticmethod
def __to_headers(in_data: typing.Tuple[typing.Tuple[str, str], ...]) -> _collections.HTTPHeaderDict:
data = tuple(t for t in in_data if t)
headers = _collections.HTTPHeaderDict()
if not data:
return headers
headers.extend(data)
return headers
@classmethod
def serialize(
cls,
in_data: typing.Union[
schemas.Schema, decimal.Decimal, int, float, str, datetime.date, datetime.datetime, None, bool, list, tuple, dict, frozendict.frozendict],
name: str
) -> _collections.HTTPHeaderDict:
if cls.schema:
cast_in_data = cls.schema(in_data)
cast_in_data = cls._json_encoder.default(cast_in_data)
"""
simple -> header
headers: PoolManager needs a mapping, tuple is close
returns headers: dict
"""
if cls.style:
value = cls._serialize_simple(cast_in_data, name, cls.explode, False)
return cls.__to_headers(((name, value),))
# cls.content will be length one
for content_type, schema in cls.content.items():
cast_in_data = schema(in_data)
cast_in_data = cls._json_encoder.default(cast_in_data)
if cls._content_type_is_json(content_type):
value = cls._serialize_json(cast_in_data)
return cls.__to_headers(((name, value),))
raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type))
@classmethod
def deserialize(
cls,
in_data: str,
name: str
) -> schemas.Schema:
if cls.schema:
"""
simple -> header
headers: PoolManager needs a mapping, tuple is close
returns headers: dict
"""
if cls.style:
extracted_data = cls._deserialize_simple(in_data, name, cls.explode, False)
return schema.from_openapi_data_oapg(extracted_data)
# cls.content will be length one
for content_type, schema in cls.content.items():
if cls._content_type_is_json(content_type):
cast_in_data = json.loads(in_data)
return schema.from_openapi_data_oapg(cast_in_data)
raise NotImplementedError('Deserialization of {} has not yet been implemented'.format(content_type))
class HeaderParameter(HeaderParameterWithoutName):
name: str
@classmethod
def serialize(
cls,
in_data: typing.Union[
schemas.Schema, decimal.Decimal, int, float, str, datetime.date, datetime.datetime, None, bool, list, tuple, dict, frozendict.frozendict]
) -> _collections.HTTPHeaderDict:
return super().serialize(
in_data,
cls.name
)
class Encoding:
def __init__(
self,
content_type: str,
headers: typing.Optional[typing.Dict[str, HeaderParameter]] = None,
style: typing.Optional[ParameterStyle] = None,
explode: bool = False,
allow_reserved: bool = False,
):
self.content_type = content_type
self.headers = headers
self.style = style
self.explode = explode
self.allow_reserved = allow_reserved
@dataclasses.dataclass
class MediaType:
"""
Used to store request and response body schema information
encoding:
A map between a property name and its encoding information.
The key, being the property name, MUST exist in the schema as a property.
The encoding object SHALL only apply to requestBody objects when the media type is
multipart or application/x-www-form-urlencoded.
"""
schema: typing.Optional[typing.Type[schemas.Schema]] = None
encoding: typing.Optional[typing.Dict[str, Encoding]] = None
@dataclasses.dataclass
class ApiResponse:
response: urllib3.HTTPResponse
body: typing.Union[schemas.Unset, schemas.Schema] = schemas.unset
headers: typing.Union[schemas.Unset, typing.Dict[str, schemas.Schema]] = schemas.unset
def __init__(
self,
response: urllib3.HTTPResponse,
body: typing.Union[schemas.Unset, schemas.Schema] = schemas.unset,
headers: typing.Union[schemas.Unset, typing.Dict[str, schemas.Schema]] = schemas.unset
):
"""
pycharm needs this to prevent 'Unexpected argument' warnings
"""
self.response = response
self.body = body
self.headers = headers
@dataclasses.dataclass
class ApiResponseWithoutDeserialization(ApiResponse):
response: urllib3.HTTPResponse
body: typing.Union[schemas.Unset, schemas.Schema] = schemas.unset
headers: typing.Union[schemas.Unset, typing.Dict[str, schemas.Schema]] = schemas.unset
class TypedDictInputVerifier:
@staticmethod
def _verify_typed_dict_inputs_oapg(cls: typing.Type[typing_extensions.TypedDict], data: typing.Dict[str, typing.Any]):
"""
Ensures that:
- required keys are present
- additional properties are not input
- value stored under required keys do not have the value schemas.unset
Note: detailed value checking is done in schema classes
"""
missing_required_keys = []
required_keys_with_unset_values = []
for required_key in cls.__required_keys__:
if required_key not in data:
missing_required_keys.append(required_key)
continue
value = data[required_key]
if value is schemas.unset:
required_keys_with_unset_values.append(required_key)
if missing_required_keys:
raise exceptions.ApiTypeError(
'{} missing {} required arguments: {}'.format(
cls.__name__, len(missing_required_keys), missing_required_keys
)
)
if required_keys_with_unset_values:
raise exceptions.ApiValueError(
'{} contains invalid unset values for {} required keys: {}'.format(
cls.__name__, len(required_keys_with_unset_values), required_keys_with_unset_values
)
)
disallowed_additional_keys = []
for key in data:
if key in cls.__required_keys__ or key in cls.__optional_keys__:
continue
disallowed_additional_keys.append(key)
if disallowed_additional_keys:
raise exceptions.ApiTypeError(
'{} got {} unexpected keyword arguments: {}'.format(
cls.__name__, len(disallowed_additional_keys), disallowed_additional_keys
)
)
T = typing.TypeVar("T")
@dataclasses.dataclass
class OpenApiResponse(JSONDetector, TypedDictInputVerifier, typing.Generic[T]):
__filename_content_disposition_pattern = re.compile('filename="(.+?)"')
response_cls: typing.Type[T]
content: typing.Optional[typing.Dict[str, MediaType]] = None
headers: typing.Optional[typing.Dict[str, HeaderParameterWithoutName]] = None
@staticmethod
def __deserialize_json(response: urllib3.HTTPResponse) -> typing.Any:
# python must be >= 3.9 so we can pass in bytes into json.loads
return json.loads(response.data)
@staticmethod
def __file_name_from_response_url(response_url: typing.Optional[str]) -> typing.Optional[str]:
if response_url is None:
return None
url_path = parse.urlparse(response_url).path
if url_path:
path_basename = os.path.basename(url_path)
if path_basename:
_filename, ext = os.path.splitext(path_basename)
if ext:
return path_basename
return None
@classmethod
def __file_name_from_content_disposition(cls, content_disposition: typing.Optional[str]) -> typing.Optional[str]:
if content_disposition is None:
return None
match = cls.__filename_content_disposition_pattern.search(content_disposition)
if not match:
return None
return match.group(1)
@classmethod
def __deserialize_application_octet_stream(
cls, response: urllib3.HTTPResponse
) -> typing.Union[bytes, io.BufferedReader]:
"""
urllib3 use cases:
1. when preload_content=True (stream=False) then supports_chunked_reads is False and bytes are returned
2. when preload_content=False (stream=True) then supports_chunked_reads is True and
a file will be written and returned
"""
if response.supports_chunked_reads():
file_name = (
cls.__file_name_from_content_disposition(response.headers.get('content-disposition'))
or cls.__file_name_from_response_url(response.geturl())
)
if file_name is None:
_fd, path = tempfile.mkstemp()
else:
path = os.path.join(tempfile.gettempdir(), file_name)
with open(path, 'wb') as new_file:
chunk_size = 1024
while True:
data = response.read(chunk_size)
if not data:
break
new_file.write(data)
# release_conn is needed for streaming connections only
response.release_conn()
new_file = open(path, 'rb')
return new_file
else:
return response.data
@staticmethod
def __deserialize_multipart_form_data(
response: urllib3.HTTPResponse
) -> typing.Dict[str, typing.Any]:
msg = email.message_from_bytes(response.data)
return {
part.get_param("name", header="Content-Disposition"): part.get_payload(
decode=True
).decode(part.get_content_charset())
if part.get_content_charset()
else part.get_payload()
for part in msg.get_payload()
}
@classmethod
def deserialize(cls, response: urllib3.HTTPResponse, configuration: configuration_module.Configuration) -> T:
content_type = response.getheader('content-type')
deserialized_body = schemas.unset
streamed = response.supports_chunked_reads()
deserialized_headers = schemas.unset
if cls.headers is not None:
cls._verify_typed_dict_inputs_oapg(cls.response_cls.headers, response.headers)
deserialized_headers = {}
for header_name, header_param in self.headers.items():
header_value = response.getheader(header_name)
if header_value is None:
continue
header_value = header_param.deserialize(header_value, header_name)
deserialized_headers[header_name] = header_value
if cls.content is not None:
if content_type not in cls.content:
raise exceptions.ApiValueError(
f"Invalid content_type returned. Content_type='{content_type}' was returned "
f"when only {str(set(cls.content))} are defined for status_code={str(response.status)}"
)
body_schema = cls.content[content_type].schema
if body_schema is None:
# some specs do not define response content media type schemas
return cls.response_cls(
response=response,
headers=deserialized_headers,
body=schemas.unset
)
if cls._content_type_is_json(content_type):
body_data = cls.__deserialize_json(response)
elif content_type == 'application/octet-stream':
body_data = cls.__deserialize_application_octet_stream(response)
elif content_type.startswith('multipart/form-data'):
body_data = cls.__deserialize_multipart_form_data(response)
content_type = 'multipart/form-data'
else:
raise NotImplementedError('Deserialization of {} has not yet been implemented'.format(content_type))
deserialized_body = body_schema.from_openapi_data_oapg(
body_data, _configuration=configuration)
elif streamed:
response.release_conn()
return cls.response_cls(
response=response,
headers=deserialized_headers,
body=deserialized_body
)
class ApiClient:
"""Generic API client for OpenAPI client library builds.
OpenAPI generic API client. This client handles the client-
server communication, and is invariant across implementations. Specifics of
the methods and models for each application are generated from the OpenAPI
templates.
NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
:param configuration: configuration_module.Configuration object for this client
:param header_name: a header to pass when making calls to the API.
:param header_value: a header value to pass when making calls to
the API.
:param cookie: a cookie to include in the header when making calls
to the API
:param pool_threads: The number of threads to use for async requests
to the API. More threads means more concurrent API requests.
"""
_pool = None
def __init__(
self,
configuration: typing.Optional[configuration_module.Configuration] = None,
header_name: typing.Optional[str] = None,
header_value: typing.Optional[str] = None,
cookie: typing.Optional[str] = None,
pool_threads: int = 1
):
if configuration is None:
configuration = configuration_module.Configuration()
self.configuration = configuration
self.pool_threads = pool_threads
self.rest_client = rest.RESTClientObject(configuration)
self.default_headers = _collections.HTTPHeaderDict()
if header_name is not None:
self.default_headers[header_name] = header_value
self.cookie = cookie
# Set default User-Agent.
self.user_agent = '{{#if httpUserAgent}}{{{httpUserAgent}}}{{/if}}{{#unless httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/python{{/unless}}'
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def close(self):
if self._pool:
self._pool.close()
self._pool.join()
self._pool = None
if hasattr(atexit, 'unregister'):
atexit.unregister(self.close)
@property
def pool(self):
"""Create thread pool on first request
avoids instantiating unused threadpool for blocking clients.