def get(self, request): """查询项目列表""" project_list = Projects.objects.all() print(project_list) # 将数据模型对象传到序列化器中将数据进行序列化,如果是多个对象需要加many=True serializer = ProjectSerializer(instance=project_list, many=True) # JsonResponse默认只能返回字典对象,如果需要返回其他对象需要将safe=False # serializer.data通过序列器中的这个data属性就可以获取到转换后的字典类型 return JsonResponse(serializer.data, safe=False)
def post(self, request): ''' 新建项目 :param request: :return: ''' '''1.从前端获取json数据并转化为Python中的dict类型数据''' # 为了严禁性,这里需要做各种复杂的校验 # 比如:是否为json、传递的项目数据是否符合要求、有些比传参数是否携带等 '''反序列化数据''' json_data = request.body.decode('utf-8') dict_data = json.loads(json_data, encoding='utf-8') '''2.校验前端输入的数据''' # 反序列化使用data参数 deserializer_data = ProjectSerializer(data=dict_data) # 调用序列化器对象的is_valid()方法来校验前端传入的参数,如果校验成功返回True,否则返回失败 # 如果raise_exception=True,那么校验失败后,会抛出异常 try: deserializer_data.is_valid(raise_exception=True) except Exception as e: # 当调用is_valid()方法后,才可以调用errors属性,获取校验失败返回的错误提示信息 return JsonResponse(deserializer_data.errors) '''3.向数据库中添加一条数据,新增项目''' # obj_pro = Projects.objects.create( # name=dict_data.get('name'), # leader=dict_data.get('leader'), # tester=dict_data.get('tester'), # developer=dict_data.get('developer'), # desc=dict_data.get('desc') # ) '''校验成功后的数据,可以使用`序列化对象.validated_data`属性来获取校验成功后的数据''' obj_pro = Projects.objects.create(**deserializer_data.validated_data) '''4.序列化数据,然后返回给前端''' # res_data = { # "id": obj_pro.id, # "name": obj_pro.name, # "leader": obj_pro.leader, # "tester": obj_pro.tester, # "developer": obj_pro.developer, # "desc": obj_pro.desc # } '''序列化使用instance参数''' serializer_data = ProjectSerializer(instance=obj_pro) return JsonResponse(serializer_data.data, status=201)
def put(self, request, pk): '''1.校验前端传递的pk(项目ID)值,类型是否正确(正整数),在数据库中是否存在''' '''2.获取指定ID为pk值的项目''' obj_pro = self.get_project(pk=pk) # 从前端获取json数据并转化为Python中的dict类型数据 # 为了严禁性,这里需要做各种复杂的校验 # 比如:是否为json、传递的项目数据是否符合要求、有些比传参数是否携带等 json_data = request.body.decode('utf-8') dict_data = json.loads(json_data, encoding='utf-8') '''3.校验前端输入的数据''' '''反序列化使用data参数''' deserializer_data = ProjectSerializer(data=dict_data) ''' 调用序列化器对象的is_valid()方法来校验前端传入的参数,如果校验成功返回True,否则返回失败 如果raise_exception=True,那么校验失败后,会抛出异常 ''' try: deserializer_data.is_valid(raise_exception=True) except Exception as e: # 当调用is_valid()方法后,才可以调用errors属性,获取校验失败返回的错误提示信息 return JsonResponse(deserializer_data.errors) '''4.通过前端传递过来的数据对字段值进行修改''' '''校验成功后的数据,可以使用`序列化对象.validated_data`属性来获取校验成功后的数据''' obj_pro.name = deserializer_data.validated_data.get('name') obj_pro.leader = deserializer_data.validated_data.get('leader') obj_pro.tester = deserializer_data.validated_data.get('tester') obj_pro.developer = deserializer_data.validated_data.get('developer') obj_pro.desc = deserializer_data.validated_data.get('desc') '''保存更新''' obj_pro.save() '''5.序列化数据,返回给前端''' # res_data = { # "id": obj_pro.id, # "name": obj_pro.name, # "leader": obj_pro.leader, # "tester": obj_pro.tester, # "developer": obj_pro.developer, # "desc": obj_pro.desc # } serializer_data = ProjectSerializer(instance=obj_pro) return JsonResponse(serializer_data.data, status=201)
def get(self, request, pk): '''1.校验前端传递的pk(项目ID)值,类型是否正确(正整数),在数据库中是否存在''' '''2.获取指定ID为pk值的项目''' obj_pro = self.get_project(pk=pk) # 3.将模型类对象转化为字典,返回给前端 '''序列化''' # res_data = { # "id": obj_pro.id, # "name": obj_pro.name, # "leader": obj_pro.leader, # "tester": obj_pro.tester, # "developer": obj_pro.developer, # "desc": obj_pro.desc # } '''通过模型类对象(或者查询集),传给instance可进行序列化操作''' '''通过序列化器ProjectSerializer对象的data属性,就可以获取序列化后的字典''' serializer_data = ProjectSerializer(instance=obj_pro) return JsonResponse(serializer_data.data)
def get(self, request): ''' 获取所有项目 :param request: :return: ''' '''1.从数据库获取所有项目信息''' obj_pro = Projects.objects.all() '''2.将数据库模型类实例转化为dict类型(嵌套dict的list)''' # project_list = [] # for project in result: # project_list.append({ # "name": project.name, # "leader": project.leader, # "tester": project.tester, # "developer": project.developer, # "desc": project.desc # }) '''如果返回给前端的是数组(多条数据)时,需要添加many=True关键字参数''' serializer_data = ProjectSerializer(instance=obj_pro, many=True) # JsonResponse第一个参数默认只能为dict字典,如果要设置为其他数据类型,需要设置safe=False '''3. 将从数据库中获取到的数据返回给前端''' return JsonResponse(serializer_data.data, safe=False)
def post(self, request): # 将传入的json格式拿到并解码为utf-8 json_data = request.body.decode('utf-8') # 将数据转为字典类型 python_data = json.loads(json_data, encoding='utf-8') # 对数据进行校验 serializer = ProjectSerializer(data=python_data) try: serializer.is_valid(raise_exception=True) except Exception as e: return JsonResponse(serializer.errors) # 1.将数据拆包传入创project对象存入数据库,使用校验器后校验后的数存放在serializer.validated_data中 # project=Projects.objects.create(**serializer.validated_data) # 2.通过序列器来保存数据到数据库中 #如果在创建序列器时传的参数是data那么调用save()方法,就是调用序列化器对象的create()方法 # serializer.save(name='qj_01') # 可以进行传参,传入的参数如果key存在更新值,不存在就添加 serializer.save() # 返回新增的数据 # serializer=ProjectSerializer(instance=project) return JsonResponse(serializer.data, status=200)
def put(self, request, pk): """更新项目""" # 判断id是否存在,并返回操作对象 project = self.get_object(pk) #将请求数据转为字典 json_data = request.body.decode('utf-8') python_Data = json.loads(json_data, encoding='utf-8') # 请求参数反序列化,和序列化 serializer = ProjectSerializer(instance=project, data=python_Data) # 对请求数据进行校验 try: # is_valid必须调用这个方法才会进行校验 serializer.is_valid(raise_exception=True) except Exception as e: # 只有进行数据校验且报错后errors才会有 return JsonResponse(serializer.errors) # 对数据进行更新 # 当创建序列化器时传了instance参数和data参数时,调用save()实际会调用实例化里面的update方法 serializer.save() return JsonResponse(serializer.data)
def post(self, request): """ mandatory field: user_token, project_name, team_id from the user_token, get the user_id and check if user is part of this org. if yes. then Okay else Validation Error :param request: django request obj :return: JSONResponse """ payload = decode_token(request.COOKIES['access_token']) user = get_user_object(username=payload["sub"]) # TODO: check if user is an admin to create a project under this org. for field in self.required_parameters: if field not in request.POST: message = "Missing mandatory parameter, {}".format(field) return HttpResponseRedirect( reverse("dashboard") + "?message={}&status={}".format(message, False), ) data = { "project_name": request.POST["project_name"], "team_id": request.POST["team_id"], } team_object = get_team_object(data["team_id"]) if team_object is None: message = "Team does not exist." return HttpResponseRedirect( reverse("dashboard") + "?message={}&status={}".format(message, False), ) payload = { "project_id": str(uuid4())[:12], "team": team_object.pk, "project_name": data['project_name'], } project_serializer = ProjectSerializer(data=payload) try: if project_serializer.is_valid(): project = project_serializer.save() if project: message = "Successfully added a new project" return HttpResponseRedirect( reverse("dashboard") + "?message={}&status={}".format(message, True), ) else: message = "Failed to create a new project" return HttpResponseRedirect( reverse("dashboard") + "?message={}&status={}".format(message, False), ) else: message = "Failed to create a new project" return HttpResponseRedirect( reverse("dashboard") + "?message={}&status={}".format(message, False), ) except Exception: message = "Failed to create a new project" return HttpResponseRedirect( reverse("dashboard") + "?message={}&status={}".format(message, False), )
def get(self, request, pk): """查询项目详情""" project = self.get_object(pk) serializer = ProjectSerializer(instance=project) return JsonResponse(serializer.data)