一、需求:公司项目需要用django写一个接口供前端vue.js展示使用,API文档要求格式如下:
{
"success": 1,
"server_unrepaired_warnings": [
{
"device_moid": "afdfb80e-64dc-11e9-8378-a4bf0103e903",
"device_name": "xmpu5",
"device_type": "xmpu5",
"device_ip": "",
"machine_room_moid": "mooooooo-oooo-oooo-oooo-defaultmachi",
"machine_room_name": "默认机房",
"code": 3011,
"level": "critical",
"description": "设备电压不在正常范围,将导致系统故障",
"start_time": "2019-05-30 21:52:14",
"resolve_time": null
},
{
"device_moid": "97ad9dde-8046-11e9-9938-a4bf0103e903",
"device_name": "longfei-hdu2",
"device_type": "hdu2",
"device_ip": "192.168.52.2",
"machine_room_moid": "mooooooo-oooo-oooo-oooo-defaultmachi",
"machine_room_name": "默认机房",
"code": 3010,
"level": "critical",
"description": "单板服务器下线",
"start_time": "2019-06-06 00:32:49",
"resolve_time": null
},
{
"device_moid": "afdfb80e-64dc-11e9-8378-a4bf0103e903",
"device_name": "xmpu5",
"device_type": "xmpu5",
"device_ip": "",
"machine_room_moid": "mooooooo-oooo-oooo-oooo-defaultmachi",
"machine_room_name": "默认机房",
"code": 3005,
"level": "important",
"description": "单板温度过高,将影响业务功能的正常运行",
"start_time": "2019-06-06 18:47:26",
"resolve_time": null
}
]
}
二、使用djangorestframework解决:
1.模型类(models.py):
class ServerWarningRepaired(models.Model):
device_moid = models.CharField(max_length=40)
device_name = models.CharField(max_length=128, blank=True, null=True)
device_type = models.CharField(max_length=36, blank=True, null=True)
device_ip = models.CharField(max_length=128, blank=True, null=True)
machine_room_moid = models.CharField(max_length=40)
machine_room_name = models.CharField(max_length=128, blank=True, null=True)
code = models.SmallIntegerField()
level = models.CharField(max_length=9)
description = models.CharField(max_length=128, blank=True, null=True)
start_time = models.DateTimeField()
resolve_time = models.DateTimeField()
class Meta:
db_table = 'server_warning_repaired'
app_label = 'warning'
2.继承serialiazers.ModelSerializer,直接指定要序列化的表模型(serializers.py):
class ServerWarningUnrepairedSerializer(serializers.ModelSerializer):
start_time, resolve_time = get_time()
class Meta:
model = ServerWarningUnrepaired
fields = ('device_moid', 'device_name', 'device_type', 'device_ip', 'machine_room_moid', 'machine_room_name', 'code', 'level', 'description', 'start_time', 'resolve_time')
3.视图层处理(views.py):
class ServerWarningUnrepairedList(APIView):
def get(self, request, *args, **kwargs):
response = {'success': 1}
server_warning_unrepaired_list = ServerWarningUnrepaired.objects.all()
server_warning_unrepaired_ser = ServerWarningUnrepairedSerializer(server_warning_unrepaired_list, many=True)
response['server_unrepaired_warnings'] = server_warning_unrepaired_ser.data
return Response(response)
三、结果显示:
参考知识:
Django RESTful API之序列化
django序列化组件