简单接口

import json
from django.shortcuts import render
from django.http import JsonResponse, Http404
from django.views import View
from interfaces.models import InterFaces
from .models import Projects
from django.db.models import Q, Count
from .serializers import ProjectsSerializer


class ProjectDetailView(View):

def get_object(self, pk):
ret = {
'msg': '数据异常',
'code': 0,
}

try:
return Projects.objects.get(id=pk)
except Exception:
raise Http404

def get(self, request, pk):

project = self.get_object(pk)
# if isinstance(one_qs, JsonResponse):
# return one_qs

# one_dic = {
# 'id': one_qs.id,
# 'name': one_qs.name,
# 'leader': one_qs.leader,
# 'desc': one_qs.desc,
# }
#
# return JsonResponse(one_dic, json_dumps_params={'ensure_ascii': False}, status=200)
"""
将模型类对象转化成instance,会返回一个序列化器类对象;
使用序列化类对象的data属性,获取序列化后的数据(字典或嵌套字典的列表);
如果传递的是查询集对象,需加上many=True。
"""
serializer_obj = ProjectsSerializer(instance=project)
return JsonResponse(serializer_obj.data, json_dumps_params={'ensure_ascii': False}, status=200)

def put(self, requests, pk):

ret = {
'msg': '数据异常',
'code': 0,
}

project = self.get_object(pk)
# if isinstance(one_qs, JsonResponse):
# return one_qs

# json数据校验
json_str_data = requests.body.decode('utf-8')
try:
python_data = json.loads(json_str_data)
except json.JSONDecodeError:
return JsonResponse(ret, json_dumps_params={'ensure_ascii': False}, status=400)

serializer_obj01 = ProjectsSerializer(data=python_data)

try:
serializer_obj01.is_valid(raise_exception=True)
except:
ret.update(serializer_obj01.errors)
return JsonResponse(ret, json_dumps_params={'ensure_ascii': False}, status=400)

# 更新模型类对象
# project.id = python_data.get('id')
# project.name = python_data.get('name')
# project.leader = python_data.get('leader')
# project.desc = python_data.get('desc')
project.id = serializer_obj01.validated_data.get('id')
project.name = serializer_obj01.validated_data.get('name')
project.leader = serializer_obj01.validated_data.get('leader')
project.desc = serializer_obj01.validated_data.get('desc')

project.save()

# 模型类对象转化为字典
# one_dic = {
# 'id': one_qs.id,
# 'name': one_qs.name,
# 'leader': one_qs.leader,
# 'desc': one_qs.desc,
# }
#
# return JsonResponse(one_dic, json_dumps_params={'ensure_ascii': False}, status=201)
serializer_obj = ProjectsSerializer(instance=project)
return JsonResponse(serializer_obj.data, json_dumps_params={'ensure_ascii': False}, status=200)

def delete(self, requests, pk):

one_qs = self.get_object(pk)
# if isinstance(one_qs, JsonResponse):
# return one_qs

one_qs.delete()

return JsonResponse(None, safe=False, status=204)


class ProjectView(View):

def get(self, requests):
qs = Projects.objects.all()
# all_list = []
# for obj in all_data:
# one_dic = {
# 'id': obj.id,
# 'name': obj.name,
# 'leader': obj.leader,
# 'desc': obj.desc,
# }
# all_list.append(one_dic)
#
# # json.dumps(ensure_ascii=False)
# return JsonResponse(all_list, safe=False, json_dumps_params={'ensure_ascii': False})
serializer_obj = ProjectsSerializer(instance=qs, many=True)
return JsonResponse(serializer_obj.data, safe=False, json_dumps_params={'ensure_ascii': False}, status=200)

def post(self, requests):
json_str_data = requests.body.decode('utf-8')

ret = {
'msg': '数据异常',
'code': 0,
}

# json校验
try:
python_data = json.loads(json_str_data)
except json.JSONDecodeError:
return JsonResponse(ret, json_dumps_params={'ensure_ascii': False}, status=400)

serializer_obj01 = ProjectsSerializer(data=python_data)
# if not serializer_obj01.is_valid():
# ret.update(serializer_obj01.errors)
# return JsonResponse(ret, json_dumps_params={'ensure_ascii': False}, status=400)
try:
serializer_obj01.is_valid(raise_exception=True)
except:
ret.update(serializer_obj01.errors)
return JsonResponse(ret, json_dumps_params={'ensure_ascii': False}, status=400)

project = Projects.objects.create(**serializer_obj01.validated_data)

# one_dic = {
# 'id': project.id,
# 'name': project.name,
# 'leader': project.leader,
# 'desc': project.desc,
# }
#
# return JsonResponse(one_dic, json_dumps_params={'ensure_ascii': False}, status=201)
serializer_obj = ProjectsSerializer(instance=project)
return JsonResponse(serializer_obj.data, json_dumps_params={'ensure_ascii': False}, status=200)


# class MyView(View):
#
# def get(self, requests):
"""
查询集:

# 查询姐相当于列表,支持正值切片,索引,for等等
# 查询集对数据库进行优化,会缓存结果
# 惰性查询
# 链式调用,性能优化

"""

# one_obj = Projects.objects.create(name='项目1', leader='李白', desc='nb项目')
# one_obj = Projects.objects.create(name='项目4', leader='王维', desc='nb项目4')
# one_data = Projects.objects.get(id=2)
# one_data = Projects.objects.all()

"""filter:查询集"""
# one_qs = Projects.objects.filter(leader='李白')
# one_qs = Projects.objects.exclude(id=2)
# one_qs = Projects.objects.filter(id__gt=2)
# one_qs = Projects.objects.filter(id__gte=2)
# one_qs = Projects.objects.filter(id__in=[1, 3])
# one_qs = Projects.objects.filter(leader__startswith='杜')
# one_qs = Projects.objects.filter(leader__istartswith='杜')
# one_qs = Projects.objects.filter(name__contains='2')
# i: 忽略大小写
# one_qs = Projects.objects.filter(name__icontains='2')
# one_qs = Projects.objects.filter(id__gte=2)
# one_qs = Projects.objects.filter(id__in=[1, 3])

"""
多个条件(与的关系):filter(desc__contains='nb', leader__startswith='李')
链式查询:与上方查询结果一致 filter(desc__contains='nb').filter(leader__startswith='李')

Q: 或 one_qs = Projects.objects.filter(Q(name__contains=1) | Q(leader__startswith='白'))
Q: 与 one_qs = Projects.objects.filter(Q(name__contains=1) & Q(leader__startswith='白'))
"""
# one_qs = Projects.objects.filter(desc__contains='nb', leader__startswith='李')
# one_qs = Projects.objects.filter(desc__contains='nb').filter(leader__startswith='李')
# one_qs = Projects.objects.filter(desc__contains='nb').exclude(leader__startswith='白')
# one_qs = Projects.objects.filter(Q(name__contains=1) | Q(leader__startswith='白'))
# one_list = []
# for i in one_qs:
# one_dic = {
# 'name': i.name,
# 'leader': i.leader,
# 'desc': i.desc,
# }
# one_list.append(one_dic)

"""
关联查询:

用子表信息查询父表数据:one_qs = Projects.objects.filter(interfaces__tester='测试3')
用父表信息查询子表数据:one_qs = InterFaces.objects.filter(project__name__contains=2)
"""
# one_qs = InterFaces.objects.filter(project__leader__contains='李')
# one_qs = InterFaces.objects.filter(project__name__contains='项目')
# one_qs = Projects.objects.filter(interfaces__name='接口2')
# one_qs = Projects.objects.filter(interfaces__tester__startswith='测试')
# print(one_qs.count())
# print(len(one_qs))
# print(one_qs.first())
# print(one_qs.last())
# print(one_qs.exists())
# one_list = []
# for i in one_qs:
# one_dic = {
# 'id': i.id,
# 'name': i.name,
# # 'leader': leader,
# 'tester': i.tester,
# # 'desc': i.desc,
# }
# one_list.append(one_dic)
#
# return JsonResponse(one_list, safe=False)
# return JsonResponse('', safe=False)

# one_qs = Projects.objects.get(pk=1)
# one_qs.leader = '苏轼'
# one_qs.save()
# one_dic = {
# 'id': one_qs.id,
# 'name': one_qs.name,
# 'leader': one_qs.leader,
# }

# one_qs = Projects.objects.filter()
# print(one_qs.values())
# < QuerySet[{'id': 1, 'name': '项目1', 'leader': '苏轼', 'desc': 'nb项目1',
# 'create_time': datetime.datetime(2020, 12, 27, 13, 28, 20, 801110,tzinfo= < UTC >), 'update_time':
# datetime.datetime(2020, 12, 29, 15, 19, 7, 391951,tzinfo= < UTC >)}, {'id': 2,......

# print(one_qs.values_list())
# [(1, '项目1', '苏轼', 'nb项目1', datetime.datetime(2020, 12, 27, 13, 28, 20, 801110, tzinfo= < UTC >),
# datetime.datetime(2020, 12, 29, 15, 19, 7, 391951, tzinfo= < UTC >)),......

# print(one_qs.values_list('id').order_by('id'))
# < QuerySet[(1,), (2,), (3,), (4,)] >

# print(one_qs.values_list('id', flat=True).order_by('id'))
# < QuerySet[1, 2, 3, 4] >

"""
raw:
可执行原生sql语句,性能更优
"""

# one_qs = Projects.objects.raw('select name, leader from tb_project ')
# print(one_qs)

# one_qs = Projects.objects.aggregate(Count('id'))
# print(type(one_qs), one_qs)

# return JsonResponse(one_dic)
# return JsonResponse('', safe=False)

# def post(self, requests):
# # one_obj = Projects.objects.create(name='项目1', leader='李白', desc='nb项目')
#
# return JsonResponse('', safe=False)
上一篇:间接部署 - 在 Linux 上使用 Nginx 托管 ASP.NET Core 网站


下一篇:一、Spring Cloud概述