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
1509 lines (1366 loc) · 57.8 KB
/
api_client.handlebars
File metadata and controls
1509 lines (1366 loc) · 57.8 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}}
from dataclasses import dataclass
from decimal import Decimal
import enum
import email
import json
import os
import io
import atexit
from multiprocessing.pool import ThreadPool
import re
import tempfile
import typing
import typing_extensions
import urllib3
from urllib3._collections import HTTPHeaderDict
from urllib.parse import urlparse, quote
from urllib3.fields import RequestField as RequestFieldBase
{{#if tornado}}
import tornado.gen
{{/if}}
import frozendict
from {{packageName}} import rest
from {{packageName}}.configuration import Configuration
from {{packageName}}.exceptions import ApiTypeError, ApiValueError
from {{packageName}}.schemas import (
NoneClass,
BoolClass,
Schema,
FileIO,
BinarySchema,
date,
datetime,
none_type,
Unset,
unset,
)
class RequestField(RequestFieldBase):
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):
if obj.as_tuple().exponent >= 0:
return int(obj)
return float(obj)
elif isinstance(obj, NoneClass):
return None
elif isinstance(obj, 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 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:
@classmethod
def _get_default_explode(cls, style: ParameterStyle) -> bool:
return False
@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 quote(str(in_data))
return str(in_data)
elif isinstance(in_data, 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 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, 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 ApiValueError('Unable to generate a ref6570 representation of {}'.format(in_data))
class StyleFormSerializer(ParameterSerializerBase):
@classmethod
def _get_default_explode(cls, style: ParameterStyle) -> bool:
if style is ParameterStyle.FORM:
return True
return super()._get_default_explode(style)
def _serialize_form(
self,
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 self._ref6570_expansion(
variable_name=name,
in_data=in_data,
explode=explode,
percent_encode=percent_encode,
prefix_separator_iterator=prefix_separator_iterator
)
class StyleSimpleSerializer(ParameterSerializerBase):
def _serialize_simple(
self,
in_data: typing.Union[None, int, float, str, bool, dict, list],
name: str,
explode: bool,
percent_encode: bool
) -> str:
prefix_separator_iterator = PrefixSeparatorIterator('', ',')
return self._ref6570_expansion(
variable_name=name,
in_data=in_data,
explode=explode,
percent_encode=percent_encode,
prefix_separator_iterator=prefix_separator_iterator
)
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
@dataclass
class ParameterBase(JSONDetector):
name: str
in_type: ParameterInType
required: bool
style: typing.Optional[ParameterStyle]
explode: typing.Optional[bool]
allow_reserved: typing.Optional[bool]
schema: typing.Optional[typing.Type[Schema]]
content: typing.Optional[typing.Dict[str, typing.Type[Schema]]]
__style_to_in_type = {
ParameterStyle.MATRIX: {ParameterInType.PATH},
ParameterStyle.LABEL: {ParameterInType.PATH},
ParameterStyle.FORM: {ParameterInType.QUERY, ParameterInType.COOKIE},
ParameterStyle.SIMPLE: {ParameterInType.PATH, ParameterInType.HEADER},
ParameterStyle.SPACE_DELIMITED: {ParameterInType.QUERY},
ParameterStyle.PIPE_DELIMITED: {ParameterInType.QUERY},
ParameterStyle.DEEP_OBJECT: {ParameterInType.QUERY},
}
__in_type_to_default_style = {
ParameterInType.QUERY: ParameterStyle.FORM,
ParameterInType.PATH: ParameterStyle.SIMPLE,
ParameterInType.HEADER: ParameterStyle.SIMPLE,
ParameterInType.COOKIE: ParameterStyle.FORM,
}
__disallowed_header_names = {'Accept', 'Content-Type', 'Authorization'}
_json_encoder = JSONEncoder()
@classmethod
def __verify_style_to_in_type(cls, style: typing.Optional[ParameterStyle], in_type: ParameterInType):
if style is None:
return
in_type_set = cls.__style_to_in_type[style]
if in_type not in in_type_set:
raise ValueError(
'Invalid style and in_type combination. For style={} only in_type={} are allowed'.format(
style, in_type_set
)
)
def __init__(
self,
name: str,
in_type: ParameterInType,
required: bool = False,
style: typing.Optional[ParameterStyle] = None,
explode: bool = False,
allow_reserved: typing.Optional[bool] = None,
schema: typing.Optional[typing.Type[Schema]] = None,
content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None
):
if schema is None and content is None:
raise ValueError('Value missing; Pass in either schema or content')
if schema and content:
raise ValueError('Too many values provided. Both schema and content were provided. Only one may be input')
if name in self.__disallowed_header_names and in_type is ParameterInType.HEADER:
raise ValueError('Invalid name, name may not be one of {}'.format(self.__disallowed_header_names))
self.__verify_style_to_in_type(style, in_type)
if content is None and style is None:
style = self.__in_type_to_default_style[in_type]
if content is not None and in_type in self.__in_type_to_default_style and len(content) != 1:
raise ValueError('Invalid content length, content length must equal 1')
self.in_type = in_type
self.name = name
self.required = required
self.style = style
self.explode = explode
self.allow_reserved = allow_reserved
self.schema = schema
self.content = content
def _serialize_json(
self,
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=self._json_encoder.compact_separators)
return json.dumps(in_data)
class PathParameter(ParameterBase, StyleSimpleSerializer):
def __init__(
self,
name: str,
required: bool = False,
style: typing.Optional[ParameterStyle] = None,
explode: bool = False,
allow_reserved: typing.Optional[bool] = None,
schema: typing.Optional[typing.Type[Schema]] = None,
content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None
):
super().__init__(
name,
in_type=ParameterInType.PATH,
required=required,
style=style,
explode=explode,
allow_reserved=allow_reserved,
schema=schema,
content=content
)
def __serialize_label(
self,
in_data: typing.Union[None, int, float, str, bool, dict, list]
) -> typing.Dict[str, str]:
prefix_separator_iterator = PrefixSeparatorIterator('.', '.')
value = self._ref6570_expansion(
variable_name=self.name,
in_data=in_data,
explode=self.explode,
percent_encode=True,
prefix_separator_iterator=prefix_separator_iterator
)
return self._to_dict(self.name, value)
def __serialize_matrix(
self,
in_data: typing.Union[None, int, float, str, bool, dict, list]
) -> typing.Dict[str, str]:
prefix_separator_iterator = PrefixSeparatorIterator(';', ';')
value = self._ref6570_expansion(
variable_name=self.name,
in_data=in_data,
explode=self.explode,
percent_encode=True,
prefix_separator_iterator=prefix_separator_iterator
)
return self._to_dict(self.name, value)
def __serialize_simple(
self,
in_data: typing.Union[None, int, float, str, bool, dict, list],
) -> typing.Dict[str, str]:
value = self._serialize_simple(
in_data=in_data,
name=self.name,
explode=self.explode,
percent_encode=True
)
return self._to_dict(self.name, value)
def serialize(
self,
in_data: typing.Union[
Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict]
) -> typing.Dict[str, str]:
if self.schema:
cast_in_data = self.schema(in_data)
cast_in_data = self._json_encoder.default(cast_in_data)
"""
simple -> path
path:
returns path_params: dict
label -> path
returns path_params
matrix -> path
returns path_params
"""
if self.style:
if self.style is ParameterStyle.SIMPLE:
return self.__serialize_simple(cast_in_data)
elif self.style is ParameterStyle.LABEL:
return self.__serialize_label(cast_in_data)
elif self.style is ParameterStyle.MATRIX:
return self.__serialize_matrix(cast_in_data)
# self.content will be length one
for content_type, schema in self.content.items():
cast_in_data = schema(in_data)
cast_in_data = self._json_encoder.default(cast_in_data)
if self._content_type_is_json(content_type):
value = self._serialize_json(cast_in_data)
return self._to_dict(self.name, value)
raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type))
class QueryParameter(ParameterBase, StyleFormSerializer):
def __init__(
self,
name: str,
required: bool = False,
style: typing.Optional[ParameterStyle] = None,
explode: typing.Optional[bool] = None,
allow_reserved: typing.Optional[bool] = None,
schema: typing.Optional[typing.Type[Schema]] = None,
content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None
):
used_style = ParameterStyle.FORM if style is None else style
used_explode = self._get_default_explode(used_style) if explode is None else explode
super().__init__(
name,
in_type=ParameterInType.QUERY,
required=required,
style=used_style,
explode=used_explode,
allow_reserved=allow_reserved,
schema=schema,
content=content
)
def __serialize_space_delimited(
self,
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 = self.get_prefix_separator_iterator()
value = self._ref6570_expansion(
variable_name=self.name,
in_data=in_data,
explode=self.explode,
percent_encode=True,
prefix_separator_iterator=prefix_separator_iterator
)
return self._to_dict(self.name, value)
def __serialize_pipe_delimited(
self,
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 = self.get_prefix_separator_iterator()
value = self._ref6570_expansion(
variable_name=self.name,
in_data=in_data,
explode=self.explode,
percent_encode=True,
prefix_separator_iterator=prefix_separator_iterator
)
return self._to_dict(self.name, value)
def __serialize_form(
self,
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 = self.get_prefix_separator_iterator()
value = self._serialize_form(
in_data,
name=self.name,
explode=self.explode,
percent_encode=True,
prefix_separator_iterator=prefix_separator_iterator
)
return self._to_dict(self.name, value)
def get_prefix_separator_iterator(self) -> typing.Optional[PrefixSeparatorIterator]:
if self.style is ParameterStyle.FORM:
return PrefixSeparatorIterator('?', '&')
elif self.style is ParameterStyle.SPACE_DELIMITED:
return PrefixSeparatorIterator('', '%20')
elif self.style is ParameterStyle.PIPE_DELIMITED:
return PrefixSeparatorIterator('', '|')
def serialize(
self,
in_data: typing.Union[
Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict],
prefix_separator_iterator: typing.Optional[PrefixSeparatorIterator] = None
) -> typing.Dict[str, str]:
if self.schema:
cast_in_data = self.schema(in_data)
cast_in_data = self._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 self.style:
# TODO update query ones to omit setting values when [] {} or None is input
if self.style is ParameterStyle.FORM:
return self.__serialize_form(cast_in_data, prefix_separator_iterator)
elif self.style is ParameterStyle.SPACE_DELIMITED:
return self.__serialize_space_delimited(cast_in_data, prefix_separator_iterator)
elif self.style is ParameterStyle.PIPE_DELIMITED:
return self.__serialize_pipe_delimited(cast_in_data, prefix_separator_iterator)
# self.content will be length one
if prefix_separator_iterator is None:
prefix_separator_iterator = self.get_prefix_separator_iterator()
for content_type, schema in self.content.items():
cast_in_data = schema(in_data)
cast_in_data = self._json_encoder.default(cast_in_data)
if self._content_type_is_json(content_type):
value = self._serialize_json(cast_in_data, eliminate_whitespace=True)
return self._to_dict(
self.name,
next(prefix_separator_iterator) + self.name + '=' + quote(value)
)
raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type))
class CookieParameter(ParameterBase, StyleFormSerializer):
def __init__(
self,
name: str,
required: bool = False,
style: typing.Optional[ParameterStyle] = None,
explode: typing.Optional[bool] = None,
allow_reserved: typing.Optional[bool] = None,
schema: typing.Optional[typing.Type[Schema]] = None,
content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None
):
used_style = ParameterStyle.FORM if style is None and content is None and schema else style
used_explode = self._get_default_explode(used_style) if explode is None else explode
super().__init__(
name,
in_type=ParameterInType.COOKIE,
required=required,
style=used_style,
explode=used_explode,
allow_reserved=allow_reserved,
schema=schema,
content=content
)
def serialize(
self,
in_data: typing.Union[
Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict]
) -> typing.Dict[str, str]:
if self.schema:
cast_in_data = self.schema(in_data)
cast_in_data = self._json_encoder.default(cast_in_data)
"""
form -> cookie
returns fields: tuple
"""
if self.style:
"""
TODO add escaping of comma, space, equals
or turn encoding on
"""
value = self._serialize_form(
cast_in_data,
explode=self.explode,
name=self.name,
percent_encode=False,
prefix_separator_iterator=PrefixSeparatorIterator('', '&')
)
return self._to_dict(self.name, value)
# self.content will be length one
for content_type, schema in self.content.items():
cast_in_data = schema(in_data)
cast_in_data = self._json_encoder.default(cast_in_data)
if self._content_type_is_json(content_type):
value = self._serialize_json(cast_in_data)
return self._to_dict(self.name, value)
raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type))
class HeaderParameter(ParameterBase, StyleSimpleSerializer):
def __init__(
self,
name: str,
required: bool = False,
style: typing.Optional[ParameterStyle] = None,
explode: bool = False,
allow_reserved: typing.Optional[bool] = None,
schema: typing.Optional[typing.Type[Schema]] = None,
content: typing.Optional[typing.Dict[str, typing.Type[Schema]]] = None
):
super().__init__(
name,
in_type=ParameterInType.HEADER,
required=required,
style=style,
explode=explode,
allow_reserved=allow_reserved,
schema=schema,
content=content
)
@staticmethod
def __to_headers(in_data: typing.Tuple[typing.Tuple[str, str], ...]) -> HTTPHeaderDict:
data = tuple(t for t in in_data if t)
headers = HTTPHeaderDict()
if not data:
return headers
headers.extend(data)
return headers
def serialize(
self,
in_data: typing.Union[
Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict.frozendict]
) -> HTTPHeaderDict:
if self.schema:
cast_in_data = self.schema(in_data)
cast_in_data = self._json_encoder.default(cast_in_data)
"""
simple -> header
headers: PoolManager needs a mapping, tuple is close
returns headers: dict
"""
if self.style:
value = self._serialize_simple(cast_in_data, self.name, self.explode, False)
return self.__to_headers(((self.name, value),))
# self.content will be length one
for content_type, schema in self.content.items():
cast_in_data = schema(in_data)
cast_in_data = self._json_encoder.default(cast_in_data)
if self._content_type_is_json(content_type):
value = self._serialize_json(cast_in_data)
return self.__to_headers(((self.name, value),))
raise NotImplementedError('Serialization of {} has not yet been implemented'.format(content_type))
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
@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[Schema]] = None
encoding: typing.Optional[typing.Dict[str, Encoding]] = None
@dataclass
class ApiResponse:
response: urllib3.HTTPResponse
body: typing.Union[Unset, Schema]
headers: typing.Union[Unset, typing.List[HeaderParameter]]
def __init__(
self,
response: urllib3.HTTPResponse,
body: typing.Union[Unset, typing.Type[Schema]],
headers: typing.Union[Unset, typing.List[HeaderParameter]]
):
"""
pycharm needs this to prevent 'Unexpected argument' warnings
"""
self.response = response
self.body = body
self.headers = headers
@dataclass
class ApiResponseWithoutDeserialization(ApiResponse):
response: urllib3.HTTPResponse
body: typing.Union[Unset, typing.Type[Schema]] = unset
headers: typing.Union[Unset, typing.List[HeaderParameter]] = unset
class OpenApiResponse(JSONDetector):
__filename_content_disposition_pattern = re.compile('filename="(.+?)"')
def __init__(
self,
response_cls: typing.Type[ApiResponse] = ApiResponse,
content: typing.Optional[typing.Dict[str, MediaType]] = None,
headers: typing.Optional[typing.List[HeaderParameter]] = None,
):
self.headers = headers
if content is not None and len(content) == 0:
raise ValueError('Invalid value for content, the content dict must have >= 1 entry')
self.content = content
self.response_cls = response_cls
@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 = 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)
def __deserialize_application_octet_stream(
self, 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 = (
self.__file_name_from_content_disposition(response.headers.get('content-disposition'))
or self.__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()
}
def deserialize(self, response: urllib3.HTTPResponse, configuration: Configuration) -> ApiResponse:
content_type = response.getheader('content-type')
deserialized_body = unset
streamed = response.supports_chunked_reads()
deserialized_headers = unset
if self.headers is not None:
# TODO add header deserialiation here
pass
if self.content is not None:
if content_type not in self.content:
raise ApiValueError(
f"Invalid content_type returned. Content_type='{content_type}' was returned "
f"when only {str(set(self.content))} are defined for status_code={str(response.status)}"
)
body_schema = self.content[content_type].schema
if body_schema is None:
# some specs do not define response content media type schemas
return self.response_cls(
response=response,
headers=deserialized_headers,
body=unset
)
if self._content_type_is_json(content_type):
body_data = self.__deserialize_json(response)
elif content_type == 'application/octet-stream':
body_data = self.__deserialize_application_octet_stream(response)
elif content_type.startswith('multipart/form-data'):
body_data = self.__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 self.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 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] = 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()
self.configuration = configuration
self.pool_threads = pool_threads
self.rest_client = rest.RESTClientObject(configuration)
self.default_headers = HTTPHeaderDict()
if header_name is not None:
self.default_headers[header_name] = header_value
self.cookie = cookie