【发布时间】:2014-02-22 16:06:28
【问题描述】:
我看到了 Flask 和 Django 的招摇文档。在 Flask 中,我可以手写设计和记录我的 API。(在参数部分下包括哪些字段是必需的、可选的等)。
这是我们在 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 Document in 一点都不好。我的主要问题是如何在 Django 中编写我的 raw-json。
在 Django 中,它会自动执行它,这不允许我自定义我的 json。 如何在 Django 上实现相同的功能?
这是 models.py 文件
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
,我的模型中没有,我该如何添加?
2) 安静类似于 1st,如果我需要添加一个接受值 b/w 3 提供的值的字段,即下拉列表。如何添加?
3) 如何添加可选字段? (因为在 PUT
请求的情况下,我可能只更新 1 个字段并将其留空,这意味着 optional
字段)。
4) 另外我该如何添加一个接受 json 字符串的字段,就像 this api 所做的那样?
谢谢
我可以通过硬编码我的 api 在 Flask 中完成所有这些事情。但是在 Django 中,它从我的模型中自动执行,但(我相信)这并没有让我能够自定义我的 api。在 Flask 中,我只需要手动编写我的 API,然后与 Swagger 集成。 Django 中是否存在同样的东西?
就像我只需要在我的 Flask 代码中添加以下 json ,它就会回答我所有的问题。
# 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'
]
},
【问题讨论】:
-
this 答案可能对你有用
标签: python django rest flask swagger