This repository has been archived by the owner on Jan 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 602
/
Copy pathintrospectors.py
1140 lines (938 loc) · 36.6 KB
/
introspectors.py
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 -*-
"""Handles the instrospection of REST Framework Views and ViewSets."""
import inspect
import re
import yaml
import importlib
from .compat import OrderedDict, strip_tags
from abc import ABCMeta, abstractmethod
from django.http import HttpRequest
from django.contrib.auth.models import AnonymousUser
from django.contrib.admindocs.utils import trim_docstring
from django.utils.encoding import smart_text
import rest_framework
from rest_framework import viewsets
from rest_framework.compat import apply_markdown
from rest_framework.utils import formatting
from django.utils import six
def get_view_description(view_cls, html=False, docstring=None):
if docstring is not None:
view_cls = type(
view_cls.__name__ + '_fake',
(view_cls,),
{'__doc__': docstring})
return rest_framework.settings.api_settings \
.VIEW_DESCRIPTION_FUNCTION(view_cls, html)
def get_default_value(field):
default_value = getattr(field, 'default', None)
if rest_framework.VERSION >= '3.0.0':
from rest_framework.fields import empty
if default_value == empty:
default_value = None
if callable(default_value):
default_value = default_value()
return default_value
class IntrospectorHelper(object):
__metaclass__ = ABCMeta
@staticmethod
def strip_yaml_from_docstring(docstring):
"""
Strips YAML from the docstring.
"""
split_lines = trim_docstring(docstring).split('\n')
cut_off = None
for index in range(len(split_lines) - 1, -1, -1):
line = split_lines[index]
line = line.strip()
if line == '---':
cut_off = index
break
if cut_off is not None:
split_lines = split_lines[0:cut_off]
return "\n".join(split_lines)
@staticmethod
def strip_params_from_docstring(docstring):
"""
Strips the params from the docstring (ie. myparam -- Some param) will
not be removed from the text body
"""
params_pattern = re.compile(r'(?:^|[^-])--(?:$|[^-])')
split_lines = trim_docstring(docstring).split('\n')
cut_off = None
for index, line in enumerate(split_lines):
line = line.strip()
if params_pattern.search(line):
cut_off = index
break
if cut_off is not None:
split_lines = split_lines[0:cut_off]
return "\n".join(split_lines)
@staticmethod
def get_serializer_name(serializer):
if serializer is None:
return None
if rest_framework.VERSION >= '3.0.0':
from rest_framework.serializers import ListSerializer
assert serializer != ListSerializer, "uh oh, what now?"
if isinstance(serializer, ListSerializer):
serializer = serializer.child
if inspect.isclass(serializer):
return serializer.__name__
return serializer.__class__.__name__
@staticmethod
def get_summary(callback, docstring=None):
"""
Returns the first sentence of the first line of the class docstring
"""
description = get_view_description(
callback, html=False, docstring=docstring) \
.split("\n")[0].split(".")[0]
description = IntrospectorHelper.strip_yaml_from_docstring(
description)
description = IntrospectorHelper.strip_params_from_docstring(
description)
description = strip_tags(get_view_description(
callback, html=True, docstring=description))
return description
class BaseViewIntrospector(object):
__metaclass__ = ABCMeta
def __init__(self, callback, path, pattern):
self.callback = callback
self.path = path
self.pattern = pattern
def get_yaml_parser(self):
parser = YAMLDocstringParser(self)
return parser
@abstractmethod
def __iter__(self):
pass
def get_iterator(self):
return self.__iter__()
def get_description(self):
"""
Returns the first sentence of the first line of the class docstring
"""
return IntrospectorHelper.get_summary(self.callback)
def get_docs(self):
return get_view_description(self.callback)
class BaseMethodIntrospector(object):
__metaclass__ = ABCMeta
PRIMITIVES = {
'integer': ['int32', 'int64'],
'number': ['float', 'double'],
'string': ['string', 'byte', 'date', 'date-time'],
'boolean': ['boolean'],
}
def __init__(self, view_introspector, method):
self.method = method
self.parent = view_introspector
self.callback = view_introspector.callback
self.path = view_introspector.path
def get_module(self):
return self.callback.__module__
def check_yaml_methods(self, yaml_methods):
missing_set = set()
for key in yaml_methods:
if key not in self.parent.methods():
missing_set.add(key)
if missing_set:
raise Exception(
"methods %s in class docstring are not in view methods %s"
% (list(missing_set), list(self.parent.methods())))
def get_yaml_parser(self):
parser = YAMLDocstringParser(self)
parent_parser = YAMLDocstringParser(self.parent)
self.check_yaml_methods(parent_parser.object.keys())
new_object = {}
new_object.update(parent_parser.object.get(self.method, {}))
new_object.update(parser.object)
parser.object = new_object
return parser
def get_extra_serializer_classes(self):
return self.get_yaml_parser().get_extra_serializer_classes(
self.callback)
def ask_for_serializer_class(self):
if hasattr(self.callback, 'get_serializer_class'):
view = self.create_view()
parser = self.get_yaml_parser()
mock_view = parser.get_view_mocker(self.callback)
view = mock_view(view)
if view is not None:
return view.get_serializer_class()
def create_view(self):
view = self.callback()
if not hasattr(view, 'kwargs'):
view.kwargs = dict()
if hasattr(self.parent.pattern, 'default_args'):
view.kwargs.update(self.parent.pattern.default_args)
view.request = HttpRequest()
view.request.user = AnonymousUser()
view.request.method = self.method
return view
def get_serializer_class(self):
parser = self.get_yaml_parser()
serializer = parser.get_serializer_class(self.callback)
if serializer is None:
serializer = self.ask_for_serializer_class()
return serializer
def get_response_serializer_class(self):
parser = self.get_yaml_parser()
serializer = parser.get_response_serializer_class(self.callback)
if serializer is None:
serializer = self.get_serializer_class()
return serializer
def get_request_serializer_class(self):
parser = self.get_yaml_parser()
serializer = parser.get_request_serializer_class(self.callback)
if serializer is None:
serializer = self.get_serializer_class()
return serializer
def get_summary(self):
# If there is no docstring on the method, get class docs
return IntrospectorHelper.get_summary(
self.callback,
self.get_docs() or self.parent.get_description())
def get_nickname(self):
""" Returns the APIView's nickname """
return rest_framework.settings.api_settings \
.VIEW_NAME_FUNCTION(self.callback, self.method).replace(' ', '_')
def get_notes(self):
"""
Returns the body of the docstring trimmed before any parameters are
listed. First, get the class docstring and then get the method's. The
methods will always inherit the class comments.
"""
docstring = ""
class_docs = get_view_description(self.callback)
class_docs = IntrospectorHelper.strip_yaml_from_docstring(class_docs)
class_docs = IntrospectorHelper.strip_params_from_docstring(class_docs)
method_docs = self.get_docs()
if class_docs is not None:
docstring += class_docs + " \n"
if method_docs is not None:
method_docs = formatting.dedent(smart_text(method_docs))
method_docs = IntrospectorHelper.strip_yaml_from_docstring(
method_docs
)
method_docs = IntrospectorHelper.strip_params_from_docstring(
method_docs
)
docstring += '\n' + method_docs
docstring = docstring.strip()
return do_markdown(docstring)
def get_parameters(self):
"""
Returns parameters for an API. Parameters are a combination of HTTP
query parameters as well as HTTP body parameters that are defined by
the DRF serializer fields
"""
params = []
path_params = self.build_path_parameters()
body_params = self.build_body_parameters()
form_params = self.build_form_parameters()
query_params = self.build_query_parameters()
if path_params:
params += path_params
if self.get_http_method() not in ["GET", "DELETE", "HEAD"]:
params += form_params
if not form_params and body_params is not None:
params.append(body_params)
if query_params:
params += query_params
return params
def get_http_method(self):
return self.method
@abstractmethod
def get_docs(self):
return ''
def retrieve_docstring(self):
"""
Attempts to fetch the docs for a class method. Returns None
if the method does not exist
"""
method = str(self.method).lower()
if not hasattr(self.callback, method):
return None
return get_view_description(getattr(self.callback, method))
def build_body_parameters(self):
serializer = self.get_request_serializer_class()
serializer_name = IntrospectorHelper.get_serializer_name(serializer)
if serializer_name is None:
return
return {
'name': serializer_name,
'type': serializer_name,
'paramType': 'body',
}
def build_path_parameters(self):
"""
Gets the parameters from the URL
"""
url_params = re.findall('/{([^}]*)}', self.path)
params = []
for param in url_params:
params.append({
'name': param,
'type': 'string',
'paramType': 'path',
'required': True
})
return params
def build_query_parameters(self):
params = []
docstring = self.retrieve_docstring() or ''
docstring += "\n" + get_view_description(self.callback)
if docstring is None:
return params
split_lines = docstring.split('\n')
for line in split_lines:
param = line.split(' -- ')
if len(param) == 2:
params.append({'paramType': 'query',
'name': param[0].strip(),
'description': param[1].strip(),
'dataType': ''})
return params
def build_form_parameters(self):
"""
Builds form parameters from the serializer class
"""
data = []
serializer = self.get_request_serializer_class()
if serializer is None:
return data
fields = serializer().get_fields()
for name, field in fields.items():
if getattr(field, 'read_only', False):
continue
data_type = get_data_type(field) or 'string'
# guess format
data_format = 'string'
if data_type in self.PRIMITIVES:
data_format = self.PRIMITIVES.get(data_type)[0]
f = {
'paramType': 'form',
'name': name,
'description': getattr(field, 'help_text', '') or '',
'type': data_type,
'format': data_format,
'required': getattr(field, 'required', False),
'defaultValue': get_default_value(field),
}
# Swagger type is a primitive, format is more specific
if f['type'] == f['format']:
del f['format']
# defaultValue of null is not allowed, it is specific to type
if f['defaultValue'] == None:
del f['defaultValue']
# Min/Max values
max_val = getattr(field, 'max_val', None)
min_val = getattr(field, 'min_val', None)
if max_val is not None and data_type == 'integer':
f['minimum'] = min_val
if max_val is not None and data_type == 'integer':
f['maximum'] = max_val
# ENUM options
if get_data_type(field) in ['multiple choice', 'choice']:
if isinstance(field.choices, list):
f['enum'] = [k for k, v in field.choices]
elif isinstance(field.choices, dict):
f['enum'] = [k for k, v in field.choices.items()]
data.append(f)
return data
def get_data_type(field):
from rest_framework import fields
if hasattr(field, 'type_label'):
if field.type_label == 'field':
return 'string'
else:
return field.type_label
elif isinstance(field, fields.BooleanField):
return 'boolean'
elif isinstance(field, fields.NullBooleanField):
return 'boolean'
elif isinstance(field, fields.URLField):
return 'url'
elif isinstance(field, fields.SlugField):
return 'slug'
elif isinstance(field, fields.ChoiceField):
return 'choice'
elif isinstance(field, fields.EmailField):
return 'email'
elif isinstance(field, fields.RegexField):
return 'regex'
elif isinstance(field, fields.DateField):
return 'date'
elif isinstance(field, fields.DateTimeField):
return 'datetime'
elif isinstance(field, fields.TimeField):
return 'time'
elif isinstance(field, fields.IntegerField):
return 'integer'
elif isinstance(field, fields.FloatField):
return 'float'
elif isinstance(field, fields.DecimalField):
return 'decimal'
elif isinstance(field, fields.ImageField):
return 'image upload'
elif isinstance(field, fields.FileField):
return 'file upload'
elif isinstance(field, fields.CharField):
return 'string'
else:
return 'string'
class APIViewIntrospector(BaseViewIntrospector):
def __iter__(self):
for method in self.methods():
yield APIViewMethodIntrospector(self, method)
def methods(self):
return self.callback().allowed_methods
class WrappedAPIViewIntrospector(BaseViewIntrospector):
def __iter__(self):
for method in self.methods():
yield WrappedAPIViewMethodIntrospector(self, method)
def methods(self):
return self.callback().allowed_methods
def get_notes(self):
class_docs = get_view_description(self.callback)
class_docs = IntrospectorHelper.strip_yaml_from_docstring(
class_docs)
class_docs = IntrospectorHelper.strip_params_from_docstring(
class_docs)
return get_view_description(
self.callback, html=True, docstring=class_docs)
def do_markdown(docstring):
# Markdown is optional
if apply_markdown:
return apply_markdown(docstring)
else:
return docstring.replace("\n\n", "<br/>")
class APIViewMethodIntrospector(BaseMethodIntrospector):
def get_docs(self):
"""
Attempts to retrieve method specific docs for an
endpoint. If none are available, the class docstring
will be used
"""
return self.retrieve_docstring()
class WrappedAPIViewMethodIntrospector(BaseMethodIntrospector):
def get_docs(self):
"""
Attempts to retrieve method specific docs for an
endpoint. If none are available, the class docstring
will be used
"""
return get_view_description(self.callback)
def get_module(self):
from rest_framework_swagger.decorators import wrapper_to_func
func = wrapper_to_func(self.callback)
return func.__module__
def get_notes(self):
return self.parent.get_notes()
def get_yaml_parser(self):
parser = YAMLDocstringParser(self)
return parser
class ViewSetIntrospector(BaseViewIntrospector):
"""Handle ViewSet introspection."""
def __init__(self, callback, path, pattern, patterns=None):
super(ViewSetIntrospector, self).__init__(callback, path, pattern)
if not issubclass(callback, viewsets.ViewSetMixin):
raise Exception("wrong callback passed to ViewSetIntrospector")
self.patterns = patterns or [pattern]
def __iter__(self):
methods = self._resolve_methods()
for method in methods:
yield ViewSetMethodIntrospector(self, methods[method], method)
def methods(self):
stuff = []
for pattern in self.patterns:
if pattern.callback:
stuff.extend(self._resolve_methods(pattern).values())
return stuff
def _resolve_methods(self, pattern=None):
from .decorators import closure_n_code, get_closure_var
if pattern is None:
pattern = self.pattern
callback = pattern.callback
try:
x = closure_n_code(callback)
while getattr(x.code, 'co_name') != 'view':
# lets unwrap!
callback = get_closure_var(callback)
x = closure_n_code(callback)
freevars = x.code.co_freevars
except (AttributeError, IndexError):
raise RuntimeError(
'Unable to use callback invalid closure/function ' +
'specified.')
else:
return x.closure[freevars.index('actions')].cell_contents
class ViewSetMethodIntrospector(BaseMethodIntrospector):
def __init__(self, view_introspector, method, http_method):
super(ViewSetMethodIntrospector, self) \
.__init__(view_introspector, method)
self.http_method = http_method.upper()
def get_http_method(self):
return self.http_method
def get_docs(self):
"""
Attempts to retrieve method specific docs for an
endpoint. If none are available, the class docstring
will be used
"""
return self.retrieve_docstring()
def create_view(self):
view = super(ViewSetMethodIntrospector, self).create_view()
if not hasattr(view, 'action'):
setattr(view, 'action', self.method)
view.request.method = self.http_method
return view
def build_query_parameters(self):
parameters = super(ViewSetMethodIntrospector, self) \
.build_query_parameters()
view = self.create_view()
if not hasattr(view, 'paginate_by'):
return parameters
if self.method == 'list' and view.paginate_by:
parameters.append({'paramType': 'query',
'name': view.page_kwarg,
'description': None,
'dataType': 'integer'})
if hasattr(view, 'paginate_by_param') and view.paginate_by_param:
parameters.append({'paramType': 'query',
'name': view.paginate_by_param,
'description': None,
'dataType': 'integer'})
return parameters
def multi_getattr(obj, attr, default=None):
"""
Get a named attribute from an object; multi_getattr(x, 'a.b.c.d') is
equivalent to x.a.b.c.d. When a default argument is given, it is
returned when any attribute in the chain doesn't exist; without
it, an exception is raised when a missing attribute is encountered.
"""
attributes = attr.split(".")
for i in attributes:
try:
obj = getattr(obj, i)
except AttributeError:
if default:
return default
else:
raise
return obj
class YAMLDocstringParser(object):
"""
Docstring parser powered by YAML syntax
This parser allows you override some parts of automatic method inspection
behaviours which are not always correct.
See the following documents for more information about YAML and Swagger:
- https://github.com/wordnik/swagger-core/wiki
- http://www.yaml.org/spec/1.2/spec.html
- https://github.com/wordnik/swagger-codegen/wiki/Creating-Swagger-JSON-from-YAML-files
1. Control over parameters
============================================================================
Define parameters and its properties in docstrings:
parameters:
- name: some_param
description: Foobar long description goes here
required: true
type: integer
paramType: form
minimum: 10
maximum: 100
- name: other_foo
paramType: query
- name: avatar
type: file
It is possible to override parameters discovered by method inspector by
defining:
`parameters_strategy` option to either `merge` or `replace`
To define different strategies for different `paramType`'s use the
following syntax:
parameters_strategy:
form: replace
query: merge
By default strategy is set to `merge`
Sometimes method inspector produces wrong list of parameters that
you might not won't to see in SWAGGER form. To handle this situation
define `paramTypes` that should be omitted
omit_parameters:
- form
2. Control over serializers
============================================================================
Once in a while you are using different serializers inside methods
but automatic method inspector cannot detect this. For that purpose there
is two explicit parameters that allows you to discard serializer detected
by method inspector OR replace it with another one
serializer: some.package.FooSerializer
omit_serializer: true
3. Custom Response Class
============================================================================
If your view is not using serializer at all but instead outputs simple
data type such as JSON you may define custom response object in method
signature like follows:
type:
name:
required: true
type: string
url:
required: false
type: url
4. Response Messages (Error Codes)
============================================================================
If you'd like to share common response errors that your APIView might throw
you can define them in docstring using following format:
responseMessages:
- code: 401
message: Not authenticated
- code: 403
message: Insufficient rights to call this procedure
5. Different models for reading and writing operations
============================================================================
Since REST Framework won't output write_only fields in responses as well as
does not require read_only fields to be provided it is worth to
automatically register 2 separate models for reading and writing operations.
Discovered serializer will be registered with `Write` or `Read` prefix.
Response Class will be automatically adjusted if serializer class was
detected by method inspector.
You can also refer to this models in your parameters:
parameters:
- name: CigarSerializer
type: WriteCigarSerializer
paramType: body
SAMPLE DOCSTRING:
============================================================================
---
# API Docs
# Note: YAML always starts with `---`
type:
name:
required: true
type: string
url:
required: false
type: url
created_at:
required: true
type: string
format: date-time
serializer: .serializers.FooSerializer
omit_serializer: false
parameters_strategy: merge
omit_parameters:
- path
parameters:
- name: name
description: Foobar long description goes here
required: true
type: string
paramType: form
- name: other_foo
paramType: query
- name: other_bar
paramType: query
- name: avatar
type: file
responseMessages:
- code: 401
message: Not authenticated
"""
PARAM_TYPES = ['header', 'path', 'form', 'body', 'query']
yaml_error = None
def __init__(self, method_introspector):
self.method_introspector = method_introspector
self.object = self.load_obj_from_docstring(
docstring=self.method_introspector.get_docs())
if self.object is None:
self.object = {}
def load_obj_from_docstring(self, docstring):
"""Loads YAML from docstring"""
split_lines = trim_docstring(docstring).split('\n')
# Cut YAML from rest of docstring
for index, line in enumerate(split_lines):
line = line.strip()
if line.startswith('---'):
cut_from = index
break
else:
return None
yaml_string = "\n".join(split_lines[cut_from:])
yaml_string = formatting.dedent(yaml_string)
try:
return yaml.load(yaml_string)
except yaml.YAMLError as e:
self.yaml_error = e
return None
def _load_class(self, cls_path, callback):
"""
Dynamically load a class from a string
"""
if not cls_path or not callback or not hasattr(callback, '__module__'):
return None
package = None
if '.' not in cls_path:
# within current module/file
class_name = cls_path
module_path = self.method_introspector.get_module()
else:
# relative or fully qualified path import
class_name = cls_path.split('.')[-1]
module_path = ".".join(cls_path.split('.')[:-1])
if cls_path.startswith('.'):
# relative lookup against current package
# ..serializers.FooSerializer
package = self.method_introspector.get_module()
class_obj = None
# Try to perform local or relative/fq import
try:
module = importlib.import_module(module_path, package=package)
class_obj = getattr(module, class_name, None)
except ImportError:
pass
# Class was not found, maybe it was imported to callback module?
# from app.serializers import submodule
# serializer: submodule.FooSerializer
if class_obj is None:
try:
module = importlib.import_module(
self.method_introspector.get_module())
class_obj = multi_getattr(module, cls_path, None)
except (ImportError, AttributeError):
raise Exception("Could not find %s, looked in %s" % (cls_path, module))
return class_obj
def get_serializer_class(self, callback):
"""
Retrieves serializer class from YAML object
"""
serializer = self.object.get('serializer', None)
try:
return self._load_class(serializer, callback)
except (ImportError, ValueError):
pass
return None
def get_extra_serializer_classes(self, callback):
"""
Retrieves serializer classes from pytype YAML objects
"""
parameters = self.object.get('parameters', [])
serializers = []
for parameter in parameters:
serializer = parameter.get('pytype', None)
if serializer is not None:
try:
serializer = self._load_class(serializer, callback)
serializers.append(serializer)
except (ImportError, ValueError):
pass
return serializers
def get_request_serializer_class(self, callback):
"""
Retrieves request serializer class from YAML object
"""
serializer = self.object.get('request_serializer', None)
try:
return self._load_class(serializer, callback)
except (ImportError, ValueError):
pass
return None
def get_response_serializer_class(self, callback):
"""
Retrieves response serializer class from YAML object
"""
serializer = self.object.get('response_serializer', None)
if isinstance(serializer, list):
serializer = serializer[0]
try:
return self._load_class(serializer, callback)
except (ImportError, ValueError):
pass
return None
def get_response_type(self):
"""
Docstring may define custom response class
"""
return self.object.get('type', None)
def get_response_messages(self):
"""
Retrieves response error codes from YAML object
"""
messages = []
response_messages = self.object.get('responseMessages', [])
for message in response_messages:
messages.append({
'code': message.get('code', None),
'message': message.get('message', None),
'responseModel': message.get('responseModel', None),
})
return messages
def get_view_mocker(self, callback):
view_mocker = self.object.get('view_mocker', lambda a: a)
if isinstance(view_mocker, six.string_types):
view_mocker = self._load_class(view_mocker, callback)
return view_mocker
def get_parameters(self, callback):
"""
Retrieves parameters from YAML object
"""
params = []
fields = self.object.get('parameters', [])
for field in fields:
param_type = field.get('paramType', None)
if param_type not in self.PARAM_TYPES:
param_type = 'form'
# Data Type & Format
# See:
# https://github.com/wordnik/swagger-core/wiki/1.2-transition#wiki-additions-2
# https://github.com/wordnik/swagger-core/wiki/Parameters
data_type = field.get('type', 'string')
pytype = field.get('pytype', None)
if pytype is not None:
try:
serializer = self._load_class(pytype, callback)
data_type = IntrospectorHelper.get_serializer_name(
serializer)
except (ImportError, ValueError):
pass
if param_type in ['path', 'query', 'header']:
if data_type not in BaseMethodIntrospector.PRIMITIVES:
data_type = 'string'
# Data Format
data_format = field.get('format', None)
flatten_primitives = [
val for sublist in BaseMethodIntrospector.PRIMITIVES.values()
for val in sublist
]
if data_format not in flatten_primitives:
formats = BaseMethodIntrospector.PRIMITIVES.get(data_type, None)
if formats:
data_format = formats[0]
else:
data_format = 'string'
f = {
'paramType': param_type,
'name': field.get('name', None),
'description': field.get('description', None),
'type': data_type,
'format': data_format,
'required': field.get('required', False),
'defaultValue': field.get('defaultValue', None),
}
# Allow Multiple Values &f=1,2,3,4
if field.get('allowMultiple'):
f['allowMultiple'] = True