Django Swagger整合 [英] Django Swagger Integration

查看:262
本文介绍了Django Swagger整合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了 Flask Django 。在Flask中,我可以设计和记录我的API手写(包括必需的字段,参数部分的可选等等)。

I saw swagger documentation of Flask and Django. In Flask I can design and document my API hand-written.(Include which fields are required, optional etc. under parameters sections).

以下是我们在Flask中的工作方式

class Todo(Resource):
    "Describing elephants"
    @swagger.operation(
        notes='some really good notes',
        responseClass=ModelClass.__name__,
        nickname='upload',
        parameters=[
            {
              "name": "body",
              "description": "blueprint object that needs to be added. YAML.",
              "required": True,
              "allowMultiple": False,
              "dataType": ModelClass2.__name__,
              "paramType": "body"
            }
          ],
        responseMessages=[
            {
              "code": 201,
              "message": "Created. The URL of the created blueprint should be in the Location header"
            },
            {
              "code": 405,
              "message": "Invalid input"
            }
          ]
        )

我可以选择要包括哪些参数,哪些不。 但是如何在Django中实现相同? Django-Swagger文档 in
不好。我的主要问题是如何在Django中编写我的raw-json。

I can chose which parameters to include, and which not. But how do I implement the same in Django? Django-Swagger Document in not good at all. My main issue is how do I write my raw-json in Django.

在Django中,它自动化它,不允许我自定义我的json。 如何在Django上实现同样的事情?

In Django it automates it which does not allows me to customize my json. How do I implement the same kind of thing on Django?

这里是 models.py 文件


Here is models.py file

class Controller(models.Model):
    id = models.IntegerField(primary_key = True)
    name = models.CharField(max_length = 255, unique = True)
    ip = models.CharField(max_length = 255, unique = True)
    installation_id = models.ForeignKey('Installation')

serializers.py

class ActionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Controller
        fields = ('installation',)

urls.py

from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from modules.actions import views as views

urlpatterns = patterns('',
    url(r'(?P<installation>[0-9]+)', views.ApiActions.as_view()),
)

views.py

class ApiActions(APIView):

    """
    Returns controllers List
    """

    model = Controller
    serializer_class = ActionSerializer 

    def get(self, request, installation,format=None):

        controllers = Controller.objects.get(installation_id = installation)
        serializer = ActionSerializer(controllers)
        return Response(serializer.data)

我的问题是

1)如果我需要添加一个字段说 xyz ,这不在我的模型中如何添加?

1) If I need to add a field say xyz, which is not in my models how do I add it?

2)安静地类似于 1st ,如果我需要添加一个接受值为b / w 3的值的字段,即一个下拉列表。如何添加?

2) Quiet similar to 1st, If i need to add a field which accepts values b/w 3 provided values,ie a dropdown. how do I add it?

3)如何添加可选字段? (因为在 PUT 请求的情况下,我可能只更新1个字段,而其余的将其留空,这意味着可选字段)。

3) How I add an optional field? (since in case of PUT request, I might only update 1 field and rest leave it blank, which means optional field).

4)另外,如何添加一个接受json字符串的字段,如

4) Also how do I add a field that accepts the json string, as this api does?

谢谢

我可以通过硬编码我的api在Flask中做所有这些事情。但是在Django中,它可以从我的模型自动化,而不是(我相信)让我可以自定义我的api。在Flask中,我只需要用手写我的API,然后与Swagger集成。 Django中是否存在同样的事情?

I can do all of these things in Flask by hardcoding my api. But in Django, it automates from my models, which does not(as I believe) gives me the access to customize my api. In Flask, I just need to write my API with hands and then integrate with the Swagger. Does this same thing exist in Django?

像我只需要在我的Flask代码中添加以下 json 它会回答我所有的问题。

Like I just need to add the following json in my Flask code and it will answer all my questions.

# Swagger json:
    "models": {
        "TodoItemWithArgs": {
            "description": "A description...",
            "id": "TodoItem",
            "properties": {
                "arg1": { # I can add any number of arguments I want as per my requirements.
                    "type": "string"
                },
                "arg2": {
                    "type": "string"
                },
                "arg3": {
                    "default": "123",
                    "type": "string"
                }
            },
            "required": [
                "arg1",
                "arg2" # arg3 is not mentioned and hence 'opional'
            ]
        },


推荐答案

Django-rest-framework确实有很多有用的实用程序类,如 serializers.ModelSerializer 你正在使用的但是这些是可选的。您可以创建完全自定义的API端点。

Django-rest-framework does have a lot of useful utility classes such as serializers.ModelSerializer which you are using. However these are optional. You can create totally custom API endpoints.

我建议您遵循 django休息教程这里。第一部分以这样的自定义视图开始

I suggest that you follow the django rest tutorial here. Part one starts with a custom view like this

from django.forms import widgets
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES


class SnippetSerializer(serializers.Serializer):
    pk = serializers.Field()  # Note: `Field` is an untyped read-only field.
    title = serializers.CharField(required=False,
                                  max_length=100)
    code = serializers.CharField(widget=widgets.Textarea,
                                 max_length=100000)
    linenos = serializers.BooleanField(required=False)
    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
                                       default='python')
    style = serializers.ChoiceField(choices=STYLE_CHOICES,
                                    default='friendly')

    def restore_object(self, attrs, instance=None):
        """
        Create or update a new snippet instance, given a dictionary
        of deserialized field values.

        Note that if we don't define this method, then deserializing
        data will simply return a dictionary of items.
        """
        if instance:
            # Update existing instance
            instance.title = attrs.get('title', instance.title)
            instance.code = attrs.get('code', instance.code)
            instance.linenos = attrs.get('linenos', instance.linenos)
            instance.language = attrs.get('language', instance.language)
            instance.style = attrs.get('style', instance.style)
            return instance

        # Create new instance
        return Snippet(**attrs)

请注意,每个API字段都是手动指定的,并由代码填充。所以他们不必与模型领域相符。

Note in particular that every API field is specified manually and populated by code here. So they do not have to correspond with model fields.

您的问题

如上所述,只需创建一个自定义序列号并添加一行

As I addressed above, just create a custom serialiser and add a line

class SnippetSerializer(serializers.Serializer):
    xyz = serializers.CharField(required=False, max_length=100)
            ...



2。对于列表中的选项,您要查找的内容是选择字段。



请参阅 Django文档选择,因为Swagger是一样的。

2. For options in a list, what you're looking for is a "choice" field.

See the Django documention on choice as Swagger is just the same.

设置kwarg required = False - 请注意, xyz 在我的例子中。

Set the kwarg required=False - note that it's set above for field xyz in my example.

有两种方法来做到这一点。

Two ways to do this.


  1. 只需在restore_object代码中接受一个文本字符串并使用JSON解析器

  2. 定义一个序列号它会消耗/创建JSON代码,并通过名称将其引用为描述这里

  1. Just accept a text string and use a JSON parser in the restore_object code
  2. Define a serialiser that consumes / creates the JSON code and refer to it by name as described here

这篇关于Django Swagger整合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆