Exemple #1
0
 def get_schema_fields(self, view):
     assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`'
     assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`'
     fields = [
         coreapi.Field(
             name=self.page_query_param,
             required=False,
             location='query',
             schema=coreschema.Integer(
                 title='Page',
                 description=force_str(self.page_query_description)
             )
         )
     ]
     if self.page_size_query_param is not None:
         fields.append(
             coreapi.Field(
                 name=self.page_size_query_param,
                 required=False,
                 location='query',
                 schema=coreschema.Integer(
                     title='Page size',
                     description=force_str(self.page_size_query_description)
                 )
             )
         )
     return fields
Exemple #2
0
 def get_schema_fields(self, view):
     assert (
         coreapi is not None
     ), "coreapi must be installed to use `get_schema_fields()`"
     assert (
         coreschema is not None
     ), "coreschema must be installed to use `get_schema_fields()`"
     return [
         coreapi.Field(
             name=self.limit_query_param,
             required=False,
             location="query",
             schema=coreschema.Integer(
                 title="Limit", description=force_str(self.limit_query_description)
             ),
         ),
         coreapi.Field(
             name=self.offset_query_param,
             required=False,
             location="query",
             schema=coreschema.Integer(
                 title="Offset", description=force_str(self.offset_query_description)
             ),
         ),
     ]
Exemple #3
0
 def get_schema_fields(self, view):
     assert (coreapi is not None
             ), "coreapi must be installed to use `get_schema_fields()`"
     assert (coreschema is not None
             ), "coreschema must be installed to use `get_schema_fields()`"
     fields = [
         coreapi.Field(
             name=self.page_query_param,
             required=False,
             location="query",
             schema=coreschema.Integer(title="Page",
                                       description=force_str(
                                           self.page_query_description)),
         )
     ]
     if self.page_size_query_param is not None:
         fields.append(
             coreapi.Field(
                 name=self.page_size_query_param,
                 required=False,
                 location="query",
                 schema=coreschema.Integer(
                     title="Page size",
                     description=force_str(
                         self.page_size_query_description),
                 ),
             ))
     return fields
Exemple #4
0
    def get_link(self, path, method, base_url):
        links = super(CreditOrganizationViewSchema,
                      self).get_link(path, method, base_url)

        if method == 'PUT':
            if path.strip('/').endswith('Status'):
                return coreapi.Link(
                    action='put',
                    url=path,
                    fields=[
                        coreapi.Field("order",
                                      required=True,
                                      location="form",
                                      schema=coreschema.Integer()),
                        coreapi.Field("status",
                                      required=True,
                                      location="form",
                                      schema=coreschema.Integer()),
                    ])

        elif method == 'POST':
            if path.strip('/').endswith('Offers'):
                return coreapi.Link(
                    action='post',
                    url=path,
                    fields=[
                        coreapi.Field("rotation_from",
                                      required=True,
                                      location="form",
                                      schema=coreschema.String()),
                        coreapi.Field("rotation_to",
                                      required=True,
                                      location="form",
                                      schema=coreschema.String()),
                        coreapi.Field("name",
                                      required=True,
                                      location="form",
                                      schema=coreschema.String()),
                        coreapi.Field("offer_type",
                                      required=True,
                                      location="form",
                                      schema=coreschema.Integer()),
                        coreapi.Field("score_min",
                                      required=True,
                                      location="form",
                                      schema=coreschema.Integer()),
                        coreapi.Field("score_max",
                                      required=True,
                                      location="form",
                                      schema=coreschema.Integer()),
                    ])

        return links
Exemple #5
0
 def get_schema_fields(self, view):
     assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`'
     assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`'
     return [
         coreapi.Field(name=self.limit_query_param,
                       required=False,
                       location='query',
                       schema=coreschema.Integer(
                           title='Limit',
                           description=force_str(
                               self.limit_query_description))),
         coreapi.Field(name=self.offset_query_param,
                       required=False,
                       location='query',
                       schema=coreschema.Integer(
                           title='Offset',
                           description=force_str(
                               self.offset_query_description)))
     ]
Exemple #6
0
def field_to_schema(field):
    title = force_text(field.label) if field.label else ''
    description = force_text(field.help_text) if field.help_text else ''

    if isinstance(field, serializers.ListSerializer):
        child_schema = field_to_schema(field.child)
        return coreschema.Array(
            items=child_schema,
            title=title,
            description=description
        )
    elif isinstance(field, serializers.Serializer):
        return coreschema.Object(
            properties=OrderedDict([
                (key, field_to_schema(value))
                for key, value
                in field.fields.items()
            ]),
            title=title,
            description=description
        )
    elif isinstance(field, serializers.ManyRelatedField):
        return coreschema.Array(
            items=coreschema.String(),
            title=title,
            description=description
        )
    elif isinstance(field, serializers.RelatedField):
        return coreschema.String(title=title, description=description)
    elif isinstance(field, serializers.MultipleChoiceField):
        return coreschema.Array(
            items=coreschema.Enum(enum=list(field.choices.keys())),
            title=title,
            description=description
        )
    elif isinstance(field, serializers.ChoiceField):
        return coreschema.Enum(
            enum=list(field.choices.keys()),
            title=title,
            description=description
        )
    elif isinstance(field, serializers.BooleanField):
        return coreschema.Boolean(title=title, description=description)
    elif isinstance(field, (serializers.DecimalField, serializers.FloatField)):
        return coreschema.Number(title=title, description=description)
    elif isinstance(field, serializers.IntegerField):
        return coreschema.Integer(title=title, description=description)

    if field.style.get('base_template') == 'textarea.html':
        return coreschema.String(
            title=title,
            description=description,
            format='textarea'
        )
    return coreschema.String(title=title, description=description)
 def get_schema_fields(self, view):
     assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`'
     assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`'
     fields = [
         coreapi.Field(name="term",
                       required=False,
                       location='query',
                       schema=coreschema.Integer(
                           title='Term',
                           description='Get classes from specific Term'))
     ]
     return fields
Exemple #8
0
    def get_schema_fields(self, _view):
        """
        return Q parameter documentation
        """
        fields = [
            coreapi.Field(
                name='bbox',
                required=False,
                location='query',
                schema=coreschema.String(
                    title=force_text('Bounding box.'),
                    description=force_text(self.bbox_desc)
                )
            )
        ]

        for filtername, desc in self.elastic_int_filters:
            fields.append(
                coreapi.Field(
                    name=filtername,
                    required=False,
                    location='query',
                    schema=coreschema.Integer(
                        title=force_text(filtername),
                        description=force_text(desc)
                    )
                )

            )

        for filtername, desc in self.elastic_char_filters:
            fields.append(
                coreapi.Field(
                    name=filtername,
                    required=False,
                    location='query',
                    schema=coreschema.String(
                        title=force_text(filtername),
                        description=force_text(desc)
                    )
                )

            )

        return fields
Exemple #9
0
 def format_field(self, value):
     dic = {"type": ""}
     error_messages = value.error_messages
     description = ""
     if isinstance(value, CharField):
         max_length = value.max_length
         min_length = value.min_length
         if max_length:
             description += "max_length is %d " % max_length
         if min_length:
             description += "min_length is %d " % min_length
         dic["type"] = "string"
         dic["schema"] = coreschema.String(title='',
                                           description=description,
                                           min_length=min_length,
                                           max_length=max_length)
     elif isinstance(value, IntegerField):
         min_value = value.min_value
         max_value = value.max_value
         if max_value:
             description += "max_value is %d " % max_value
         if min_value:
             description += "min_value is %d " % min_value
         dic["schema"] = coreschema.Integer(title='',
                                            description=description,
                                            minimum=min_value,
                                            maximum=max_value)
         dic["type"] = "integer"
     elif isinstance(value, ChoiceField):
         choices = value._choices
         description += str(choices).strip('[]')
         choice_list = set([k[0] for k in choices])
         dic["type"] = "enum"
         dic["schema"] = coreschema.Enum(title='',
                                         description=description,
                                         enum=choice_list)
     else:
         dic["type"] = "string"
         dic["schema"] = coreschema.String(title='',
                                           description=description)
     dic["description"] = description + value.help_text
     return dic
    def test_field_to_schema(self):
        label = 'Test label'
        help_text = 'This is a helpful test text'

        cases = [
            # tuples are ([field], [expected schema])
            # TODO: Add remaining cases
            (
                serializers.BooleanField(label=label, help_text=help_text),
                coreschema.Boolean(title=label, description=help_text)
            ),
            (
                serializers.DecimalField(1000, 1000, label=label, help_text=help_text),
                coreschema.Number(title=label, description=help_text)
            ),
            (
                serializers.FloatField(label=label, help_text=help_text),
                coreschema.Number(title=label, description=help_text)
            ),
            (
                serializers.IntegerField(label=label, help_text=help_text),
                coreschema.Integer(title=label, description=help_text)
            ),
            (
                serializers.DateField(label=label, help_text=help_text),
                coreschema.String(title=label, description=help_text, format='date')
            ),
            (
                serializers.DateTimeField(label=label, help_text=help_text),
                coreschema.String(title=label, description=help_text, format='date-time')
            ),
            (
                serializers.JSONField(label=label, help_text=help_text),
                coreschema.Object(title=label, description=help_text)
            ),
        ]

        for case in cases:
            self.assertEqual(field_to_schema(case[0]), case[1])
 def test_anonymous_request(self):
     client = APIClient()
     response = client.get('/', HTTP_ACCEPT='application/coreapi+json')
     assert response.status_code == 200
     expected = coreapi.Document(
         url='http://testserver/',
         title='Example API',
         content={
             'example': {
                 'list':
                 coreapi.Link(
                     url='/example/',
                     action='get',
                     fields=[
                         coreapi.Field(
                             'page',
                             required=False,
                             location='query',
                             schema=coreschema.Integer(
                                 title='Page',
                                 description=
                                 'A page number within the paginated result set.'
                             )),
                         coreapi.Field(
                             'page_size',
                             required=False,
                             location='query',
                             schema=coreschema.Integer(
                                 title='Page size',
                                 description=
                                 'Number of results to return per page.')),
                         coreapi.Field(
                             'ordering',
                             required=False,
                             location='query',
                             schema=coreschema.String(
                                 title='Ordering',
                                 description=
                                 'Which field to use when ordering the results.'
                             ))
                     ]),
                 'custom_list_action':
                 coreapi.Link(url='/example/custom_list_action/',
                              action='get'),
                 'custom_list_action_multiple_methods': {
                     'read':
                     coreapi.Link(
                         url='/example/custom_list_action_multiple_methods/',
                         action='get')
                 },
                 'read':
                 coreapi.Link(url='/example/{id}/',
                              action='get',
                              fields=[
                                  coreapi.Field('id',
                                                required=True,
                                                location='path',
                                                schema=coreschema.String())
                              ])
             }
         })
     assert response.data == expected
    def test_schema_for_regular_views(self):
        """
        Ensure that schema generation works for ViewSet classes
        with method limitation by Django CBV's http_method_names attribute
        """
        generator = SchemaGenerator(title='Example API',
                                    patterns=self.patterns)
        request = factory.get('/example1/')
        schema = generator.get_schema(Request(request))

        expected = coreapi.Document(
            url='http://testserver/example1/',
            title='Example API',
            content={
                'example1': {
                    'list':
                    coreapi.Link(
                        url='/example1/',
                        action='get',
                        fields=[
                            coreapi.Field(
                                'page',
                                required=False,
                                location='query',
                                schema=coreschema.Integer(
                                    title='Page',
                                    description=
                                    'A page number within the paginated result set.'
                                )),
                            coreapi.Field(
                                'page_size',
                                required=False,
                                location='query',
                                schema=coreschema.Integer(
                                    title='Page size',
                                    description=
                                    'Number of results to return per page.')),
                            coreapi.Field(
                                'ordering',
                                required=False,
                                location='query',
                                schema=coreschema.String(
                                    title='Ordering',
                                    description=
                                    'Which field to use when ordering the results.'
                                ))
                        ]),
                    'custom_list_action':
                    coreapi.Link(url='/example1/custom_list_action/',
                                 action='get'),
                    'custom_list_action_multiple_methods': {
                        'read':
                        coreapi.Link(
                            url=
                            '/example1/custom_list_action_multiple_methods/',
                            action='get')
                    },
                    'read':
                    coreapi.Link(url='/example1/{id}/',
                                 action='get',
                                 fields=[
                                     coreapi.Field('id',
                                                   required=True,
                                                   location='path',
                                                   schema=coreschema.String())
                                 ])
                }
            })
        assert schema == expected
 def test_authenticated_request(self):
     client = APIClient()
     client.force_authenticate(MockUser())
     response = client.get('/', HTTP_ACCEPT='application/coreapi+json')
     assert response.status_code == 200
     expected = coreapi.Document(
         url='http://testserver/',
         title='Example API',
         content={
             'example': {
                 'list':
                 coreapi.Link(
                     url='/example/',
                     action='get',
                     fields=[
                         coreapi.Field(
                             'page',
                             required=False,
                             location='query',
                             schema=coreschema.Integer(
                                 title='Page',
                                 description=
                                 'A page number within the paginated result set.'
                             )),
                         coreapi.Field(
                             'page_size',
                             required=False,
                             location='query',
                             schema=coreschema.Integer(
                                 title='Page size',
                                 description=
                                 'Number of results to return per page.')),
                         coreapi.Field(
                             'ordering',
                             required=False,
                             location='query',
                             schema=coreschema.String(
                                 title='Ordering',
                                 description=
                                 'Which field to use when ordering the results.'
                             ))
                     ]),
                 'create':
                 coreapi.Link(
                     url='/example/',
                     action='post',
                     encoding='application/json',
                     fields=[
                         coreapi.Field(
                             'a',
                             required=True,
                             location='form',
                             schema=coreschema.String(
                                 title='A',
                                 description='A field description')),
                         coreapi.Field('b',
                                       required=False,
                                       location='form',
                                       schema=coreschema.String(title='B'))
                     ]),
                 'read':
                 coreapi.Link(url='/example/{id}/',
                              action='get',
                              fields=[
                                  coreapi.Field('id',
                                                required=True,
                                                location='path',
                                                schema=coreschema.String())
                              ]),
                 'custom_action':
                 coreapi.Link(
                     url='/example/{id}/custom_action/',
                     action='post',
                     encoding='application/json',
                     description='A description of custom action.',
                     fields=[
                         coreapi.Field('id',
                                       required=True,
                                       location='path',
                                       schema=coreschema.String()),
                         coreapi.Field('c',
                                       required=True,
                                       location='form',
                                       schema=coreschema.String(title='C')),
                         coreapi.Field('d',
                                       required=False,
                                       location='form',
                                       schema=coreschema.String(title='D')),
                     ]),
                 'custom_list_action':
                 coreapi.Link(url='/example/custom_list_action/',
                              action='get'),
                 'custom_list_action_multiple_methods': {
                     'read':
                     coreapi.Link(
                         url='/example/custom_list_action_multiple_methods/',
                         action='get'),
                     'create':
                     coreapi.Link(
                         url='/example/custom_list_action_multiple_methods/',
                         action='post')
                 },
                 'update':
                 coreapi.Link(
                     url='/example/{id}/',
                     action='put',
                     encoding='application/json',
                     fields=[
                         coreapi.Field('id',
                                       required=True,
                                       location='path',
                                       schema=coreschema.String()),
                         coreapi.Field(
                             'a',
                             required=True,
                             location='form',
                             schema=coreschema.String(
                                 title='A',
                                 description=('A field description'))),
                         coreapi.Field('b',
                                       required=False,
                                       location='form',
                                       schema=coreschema.String(title='B'))
                     ]),
                 'partial_update':
                 coreapi.Link(
                     url='/example/{id}/',
                     action='patch',
                     encoding='application/json',
                     fields=[
                         coreapi.Field('id',
                                       required=True,
                                       location='path',
                                       schema=coreschema.String()),
                         coreapi.Field(
                             'a',
                             required=False,
                             location='form',
                             schema=coreschema.String(
                                 title='A',
                                 description='A field description')),
                         coreapi.Field('b',
                                       required=False,
                                       location='form',
                                       schema=coreschema.String(title='B'))
                     ]),
                 'delete':
                 coreapi.Link(url='/example/{id}/',
                              action='delete',
                              fields=[
                                  coreapi.Field('id',
                                                required=True,
                                                location='path',
                                                schema=coreschema.String())
                              ])
             }
         })
     assert response.data == expected
Exemple #14
0
                        status=status.HTTP_404_NOT_FOUND)

    return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)


@api_view(['GET'])
@authentication_classes((OAuth2Authentication, BasicAuthentication))
@permission_classes((IsAuthenticated, HasApiPermission))
@schema(
    MethodSchema(
        manual_fields={
            'GET': [
                coreapi.Field(name='center_id',
                              location='query',
                              required=False,
                              schema=coreschema.Integer())
            ]
        }))
def group_list(request, format=None):
    if request.method == 'GET':
        args = {
            'req_user': request.user,
            'center_id': request.GET.get('center_id'),
        }
        dic = api_group_get_list(args)
        if dic['res']:
            return Response(dic['list'], status=status.HTTP_200_OK)
        return Response(status=status.HTTP_404_NOT_FOUND)
    return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)

Exemple #15
0
class CreateQuizAPIView(generics.CreateAPIView):
    if coreapi_schema.is_enabled():
        schema = ManualSchema(
            fields=[
                coreapi.Field(
                    name="title",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Title",
                        description="name of a quiz",
                    ),
                ),
                coreapi.Field(
                    name="quiz_type",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Type of a quiz",
                        description="Type of a quiz",
                    ),
                ),
                coreapi.Field(
                    name="timestamp",
                    required=True,
                    location='form',
                    schema=coreschema.Integer(
                        title="Timestamp",
                        description="timestamp",
                    ),
                ),
                coreapi.Field(
                    name="goal",
                    required=True,
                    location='form',
                    schema=coreschema.Integer(
                        title="Goal",
                        description="goal for the users",
                    ),
                ),
                coreapi.Field(
                    name="indicator_value",
                    required=True,
                    location='form',
                    schema=coreschema.Number(
                        title="Indicator value",
                        description="indicator value",
                    ),
                ),
                coreapi.Field(
                    name="author",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Author username",
                        description="author username",
                    ),
                ),
                coreapi.Field(
                    name="description",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="question description",
                        description="description",
                    ),
                ),
                coreapi.Field(
                    name="vote_detail",
                    required=True,
                    location='form',
                    schema=coreschema.Object(
                        title="Vote detail",
                        description="vote details in json format",
                    ),
                ),
            ],
            encoding="application/json",
        )
    permission_classes = (permissions.AllowAny, )
    serializer_class = serializers.QuizSerializer
    queryset = models.Vote.objects.all()
Exemple #16
0
    def get_link(self, path, method, base_url):
        links = super(PartnerViewSchema, self).get_link(path, method, base_url)

        if method == 'POST':
            if path.strip('/').endswith('Worksheets'):
                return coreapi.Link(
                    action='post',
                    url=path,
                    fields=[
                        coreapi.Field("last_name",
                                      required=True,
                                      location="form",
                                      schema=coreschema.String()),
                        coreapi.Field("first_name",
                                      required=True,
                                      location="form",
                                      schema=coreschema.String()),
                        coreapi.Field("middle_name",
                                      required=True,
                                      location="form",
                                      schema=coreschema.String()),
                        coreapi.Field("dob",
                                      required=True,
                                      location="form",
                                      schema=coreschema.String()),
                        coreapi.Field("phone_number",
                                      required=True,
                                      location="form",
                                      schema=coreschema.String()),
                        coreapi.Field("passport_number",
                                      required=True,
                                      location="form",
                                      schema=coreschema.String()),
                        coreapi.Field("score",
                                      required=True,
                                      location="form",
                                      schema=coreschema.Integer()),
                    ])

            elif path.strip('/').endswith('Orders'):
                return coreapi.Link(
                    action='post',
                    url=path,
                    fields=[
                        coreapi.Field("worksheet",
                                      description="Worksheet Id",
                                      required=True,
                                      location="form",
                                      schema=coreschema.Integer()),
                        coreapi.Field("offer",
                                      description="Offer Id",
                                      required=True,
                                      location="form",
                                      schema=coreschema.Integer()),
                    ])

            elif path.strip('/').endswith('SendOrder'):
                return coreapi.Link(action='post',
                                    url=path,
                                    fields=[
                                        coreapi.Field(
                                            "order",
                                            description="Order Id",
                                            required=True,
                                            location="form",
                                            schema=coreschema.Integer()),
                                    ])

        elif method == 'GET':
            if path.strip('/').endswith('Worksheets'):
                return coreapi.Link(
                    action='get',
                    url=path,
                    description="""
                    Use model kind filter:
                    __exact,
                    __startswith,
                    __in,
                    __gte, __gt, __lte, __lt,
                    ...
                    """,
                    fields=[
                        coreapi.Field("last_name",
                                      required=False,
                                      location="query",
                                      schema=coreschema.String()),
                        coreapi.Field("first_name",
                                      required=False,
                                      location="query",
                                      schema=coreschema.String()),
                        coreapi.Field("middle_name",
                                      required=False,
                                      location="query",
                                      schema=coreschema.String()),
                        coreapi.Field("dob",
                                      required=False,
                                      location="query",
                                      schema=coreschema.String()),
                        coreapi.Field("phone_number",
                                      required=False,
                                      location="query",
                                      schema=coreschema.String()),
                        coreapi.Field("passport_number",
                                      required=False,
                                      location="query",
                                      schema=coreschema.String()),
                        coreapi.Field("score",
                                      required=False,
                                      location="query",
                                      schema=coreschema.Integer()),
                        coreapi.Field("order_by",
                                      required=False,
                                      location="query",
                                      schema=coreschema.String()),
                    ])

        return links
Exemple #17
0
class SubmitView(APIView):
    """
    提交
    """
    permission_classes = (IsAuthenticated,)
    schema = AutoSchema(manual_fields=[
        coreapi.Field(name='problem',
                      required=True,
                      location='form',
                      schema=coreschema.Integer(title='problem',
                                                description='要提交的题目ID')),
        coreapi.Field(name='submit_files',
                      required=True,
                      location='form',
                      schema=coreschema.Array(title='submit_files',
                                              items=coreschema.Integer,
                                              description='要提交的文件(代码等)')),
    ])

    def post(self, request, *args):
        # Fix bug: must check permission first
        self.check_permissions(request)

        # put the user segment in, ref: BaseSerializer docstring
        # Fix bug: AttributeError: This QueryDict instance is immutable
        # ref: https://stackoverflow.com/questions/44717442/this-querydict-instance-is-immutable
        data = request.data.copy()
        data['user'] = request.user.id
        serializer = SubmissionSerializer(data=data)

        # print(request.data)
        # print(serializer.initial_data)
        try:
            serializer.is_valid(True)

            # (Optional) Checking for deadline time
            ddl = Problem.objects.filter(id=data['problem'])[0].deadline_time
            if ddl is not None and ddl < django.utils.timezone.now():
                # Whoops, you dare submitting it over ddl!
                return Response("You've submitted it after deadline! {}".format(str(ddl)),
                status.HTTP_400_BAD_REQUEST)

            subm = serializer.save()

            # Instantiate judge task for all testcases
            # Get all test cases related to this problem
            prob_id = serializer.data['problem']
            subm_id = subm.id
            # print("{} {}".format(prob_id, subm_id))
            prob = Problem.objects.filter(id=prob_id).first()
            if prob == None:
                return Response('No such problem', status.HTTP_404_NOT_FOUND)

            for case in prob.get_testcases():
                # Create a new SubmissionResult structure
                subm_res = SubmissionResult.objects.create(
                    status='PENDING',
                    submission=subm,
                    testcase=case,
                    grade=0,
                    log="",
                    app_data="",
                    possible_failure='NA'
                )

                do_judge_task.delay(subm_id, case.id, subm_res.id)

            #do_judge_task(serializer.data['id'], serializer.data[''])
            return Response(serializer._data, status.HTTP_201_CREATED)
        except Exception as e:
            return Response(str(e), status.HTTP_500_INTERNAL_SERVER_ERROR)
Exemple #18
0
def field_to_schema(field):
    title = force_text(field.label) if field.label else ''
    description = force_text(field.help_text) if field.help_text else ''

    if isinstance(field, (serializers.ListSerializer, serializers.ListField)):
        child_schema = field_to_schema(field.child)
        return coreschema.Array(items=child_schema,
                                title=title,
                                description=description)
    elif isinstance(field, serializers.DictField):
        return coreschema.Object(title=title, description=description)
    elif isinstance(field, serializers.Serializer):
        return coreschema.Object(properties=OrderedDict([
            (key, field_to_schema(value))
            for key, value in field.fields.items()
        ]),
                                 title=title,
                                 description=description)
    elif isinstance(field, serializers.ManyRelatedField):
        return coreschema.Array(items=coreschema.String(),
                                title=title,
                                description=description)
    elif isinstance(field, serializers.PrimaryKeyRelatedField):
        schema_cls = coreschema.String
        model = getattr(field.queryset, 'model', None)
        if model is not None:
            model_field = model._meta.pk
            if isinstance(model_field, models.AutoField):
                schema_cls = coreschema.Integer
        return schema_cls(title=title, description=description)
    elif isinstance(field, serializers.RelatedField):
        return coreschema.String(title=title, description=description)
    elif isinstance(field, serializers.MultipleChoiceField):
        return coreschema.Array(
            items=coreschema.Enum(enum=list(field.choices)),
            title=title,
            description=description)
    elif isinstance(field, serializers.ChoiceField):
        return coreschema.Enum(enum=list(field.choices),
                               title=title,
                               description=description)
    elif isinstance(field, serializers.BooleanField):
        return coreschema.Boolean(title=title, description=description)
    elif isinstance(field, (serializers.DecimalField, serializers.FloatField)):
        return coreschema.Number(title=title, description=description)
    elif isinstance(field, serializers.IntegerField):
        return coreschema.Integer(title=title, description=description)
    elif isinstance(field, serializers.DateField):
        return coreschema.String(title=title,
                                 description=description,
                                 format='date')
    elif isinstance(field, serializers.DateTimeField):
        return coreschema.String(title=title,
                                 description=description,
                                 format='date-time')
    elif isinstance(field, serializers.JSONField):
        return coreschema.Object(title=title, description=description)

    if field.style.get('base_template') == 'textarea.html':
        return coreschema.String(title=title,
                                 description=description,
                                 format='textarea')

    return coreschema.String(title=title, description=description)
    def test_schema_for_regular_views(self):
        """
        Ensure that AutoField foreign keys are output as Integer.
        """
        generator = SchemaGenerator(title='Example API', patterns=self.patterns)
        schema = generator.get_schema()

        expected = coreapi.Document(
            url='',
            title='Example API',
            content={
                'example': {
                    'create': coreapi.Link(
                        url='/example/',
                        action='post',
                        encoding='application/json',
                        fields=[
                            coreapi.Field('name', required=True, location='form', schema=coreschema.String(title='Name')),
                            coreapi.Field('target', required=True, location='form', schema=coreschema.Integer(description='Target', title='Target')),
                        ]
                    )
                }
            }
        )
        assert schema == expected