def get(self, request ,*args, **kwargs): # 根据id 查询model对象 emp_id = kwargs.get('id') if emp_id: # 查询单个 emp_obj = Employee.objects.get(pk=emp_id) # 使用序列化器完成对象的序列化 emp_seria = EmployeeSerializer(emp_obj) return Response({ 'status':200, 'message':'查询单个员工成功', 'results':emp_seria.data },status=200) else: emp_obj_all = Employee.objects.all() # 序列化多个对象时,需要指定属性many=True emp_data = EmployeeSerializer(emp_obj_all, many=True).data # print(emp_data) return Response({ 'status':200, 'message':'查询所有员工成功', 'results':emp_data })
def get(self, request, *args, **kwargs): emp_id = kwargs.get("id") if emp_id: # 查询单个 emp_obj = Employee.objects.get(pk=emp_id) # 使用序列化器完成对象的序列化 # .data 将序列化器中的数据打包成字典返回 employee_serializer = EmployeeSerializer(emp_obj).data return Response({ "status": 200, "message": "查询单个员工成功", "results": employee_serializer }) else: employee_objects_all = Employee.objects.all() # 在序列化多个对象时 需要制定属性many=True emp_data = EmployeeSerializer(employee_objects_all, many=True).data print(emp_data) return Response({ "status": 200, "message": "查询所有员工成功", "results": emp_data })
def list(self, request, *args, **kwargs): queryset = self.get_queryset() today_year = date.today().year #filter the queryset older = queryset.latest('birth_date') younger = queryset.earliest('birth_date') #calculate ages older_age = today_year - older.birth_date.year younger_age = today_year - younger.birth_date.year average = (younger_age + older_age) / 2 #serialize objects younger_s = EmployeeSerializer(younger) older_s = EmployeeSerializer(older) #add top level info data = { 'younger': younger_s.data, 'older': older_s.data, 'average': average } return Response(data)
def add_employee(request): status1 = {} errors = {} print "ddddddddddd" if request.method == 'PUT': serializer = EmployeeSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.data) elif request.method == 'POST': serializer = EmployeeSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() print "1111111" message = "successfully created" status1['message'] = "successfully created" return Response(status1, status=status.HTTP_201_CREATED) else: print "2222222222" for err in serializer.errors: errors['error'] = err return Response(errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, *args, **kwargs): serializer = EmployeeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return response.Response(serializer.data, status=status.HTTP_201_CREATED) return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, company_id, pk, format=None): employee = Employee.objects.get(company_id=company_id, pk=pk) serializer = EmployeeSerializer(employee, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request ,*args, **kwargs): # 获取前端传递的参数 request_data = request.data # 前端传递的数据进行入库时 需要判断数据的格式是否合法 if not isinstance(request_data, dict) or request_data == {}: return Response({ 'status':400, 'message':'参数有误' },status=400) serializer = EmployeeDeSerializer(data=request_data) if(serializer.is_valid()): emp_ser = serializer.save() return Response({ 'status':200, 'message':'success', 'results':EmployeeSerializer(emp_ser).data },status=200) else: return Response({ 'status':400, 'message':'员工添加失败', 'results':serializer.errors })
def authenticate_user(request): try: username = request.data['username'] password = request.data['password'] user = Employee.objects.get(username=username, password=password) if user: try: payload = jwt_payload_handler(user) token = jwt.encode(payload, settings.SECRET_KEY) serializer = EmployeeSerializer(user) user_details = {'user': serializer.data, 'token': token} user_logged_in.send(sender=user.__class__, request=request, user=user) return Response(user_details, status=status.HTTP_200_OK) except Exception as e: raise e else: res = {'error': 'can not authenticate with the given credentials'} return Response(res, status=status.HTTP_403_FORBIDDEN) except KeyError: res = {'error': 'please provide a email and a password'} return Response(res)
def post(self, request, *args, **kwargs): # 获取前端传递的参数 request_data = request.data # print(request_data) #前端传递的数据进行入库时,需要判断数据的格式是否合法 if not isinstance(request_data, dict) or request_data == {}: return Response({ "status": 400, "message": "参数有误", }) # 使用序列化器完成数据库的反序列化 # 在数据进行反序列化的时候需要指定关键字data serializer = EmployeeDeSerializer(data=request_data) if serializer.is_valid(): # 进行数据保存 # 调用save()方法进行数据库的保存 必须重写create()方法 save = serializer.save() return Response({ "status": 200, "message": "员工添加成功", "results": EmployeeSerializer(save).data }) else: return Response({ "status": 400, "message": "员工添加失败", })
def post(self, request, *args, **kwargs): # 获取前端传递的参数 request_data = request.data # 前端传递的数据进行入库时 需要判断数据的格式是否合法 if not isinstance(request_data, dict) or request_data == {}: return Response({ "status": 400, "message": "参数有误", }) # 使用序列化器完成数据库的反序列化 # 在数据进行反序列化的时候需要指定关键字 data serializer = EmployeeDeSerializer(data=request_data) # 需要对反序列化的数据进行校验 通过is_valid() 方法来对传递过来的参数进行校验 校验合法时才会返回True if serializer.is_valid(): # 调用save()方法进行数据的保存 必须重写create()方法 emp_ser = serializer.save() print(emp_ser) return Response({ "status": 200, "message": "员工添加成功", "results": EmployeeSerializer(emp_ser).data }) else: return Response({ "status": 400, "message": "员工添加失败", # 保存失败的信息会包含在 .errors中 "results": serializer.errors })
def organization_employees(request, pk): current_user = request.user if current_user.organization_id != pk or current_user.position not in PERMITTED_POSITIONS: return JsonResponse({'message': 'Отказано в доступе'}, status=status.HTTP_403_FORBIDDEN) employees = Employee.objects.filter( Q(organization_id=current_user.organization_id), Q(organization_id=pk)) serializer = EmployeeSerializer(employees, many=True) return JsonResponse(serializer.data, safe=False)
def participate(request): try: employee = request.data.get('employee') employeeSerializer = EmployeeSerializer(data=employee) if employeeSerializer.is_valid(): employeeSerializer.save() else: return JsonResponse({'error': "Objetos não criados"}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return JsonResponse({'employee': employeeSerializer.data}, safe=False, status=status.HTTP_201_CREATED) except IntegrityError: return bad_request(request) except Exception as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def get(self, request, *args, **kwargs): user_id = kwargs.get("pk") if user_id: emp_obj = Employee.objects.get(pk=user_id) emp_ser = EmployeeSerializer(emp_obj) data = emp_ser.data return Response({ "status": 200, "msg": "查询单个员工成功", "results": data, }) else: emp_list = Employee.objects.all() emp_list_ser = EmployeeSerializer(emp_list, many=True).data return Response({ "status": 200, "msg": "查询所有员工成功", "results": emp_list_ser, })
def list(self, request, *args, **kwargs): queryset = self.get_queryset() #filter the queryset lowest = queryset.order_by('salary').first() highest = queryset.order_by('salary').last() average = (lowest.salary + highest.salary) / 2 #serialize objects highest_s = EmployeeSerializer(highest) lowest_s = EmployeeSerializer(lowest) #add top level info data = { 'highest': highest_s.data, 'lowest': lowest_s.data, 'average': average } return Response(data)
def get(self, request, *args, **kwargs): user_id = kwargs.get('id') if user_id: emp = Employee.objects.get(pk=user_id) '''开始自动序列化''' emp_ser = EmployeeSerializer(emp).data return Response({ "status": 200, "message": '查询单个成功', "result": emp_ser }) else: '''开始查询所有''' emp_all = Employee.objects.all() emp_all = EmployeeSerializer(emp_all, many=True).data return Response({ "status": 200, "message": '查询全部员工成功', "result": emp_all, })
def list_participants(request): """ List all employees :param request: :return: """ participants = Employee.objects.all() print(participants) serializer = EmployeeSerializer(participants, many=True) return JsonResponse({'participants': serializer.data}, safe=False, status=status.HTTP_200_OK)
def post(self, request, company_id): try: group_employee_ids = list( Group.objects.filter(name="employee").values_list('id', flat=True)) request.data["groups"] = group_employee_ids request.data["password"] = make_password( password=request.data["password"]) serializer = EmployeeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except Exception as a: print(a) return JsonResponse( {"detail": "An error occurred on the server" + str(a)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def get(self, request, *args, **kwargs): emp_id = kwargs.get("id") if emp_id: emp_obj = Employee.objects.get(pk=emp_id) # 使用序列化器完成对象的序列化 employee_serializer = EmployeeSerializer(emp_obj).data print(employee_serializer) return Response({ "status": 200, "message": "查询所有用户成功", "results": employee_serializer }) else: employee_objects_all = Employee.objects.all() emp_data = EmployeeSerializer(employee_objects_all, many=True).data print(emp_data) return Response({ "status": 400, "message": "查询失败", "results": emp_data })
def detail(request, pk): """Retrieve, update or delete a employee.""" try: employee = Employee.objects.get(employee_id=pk) except Employee.DoesNotExist: return Response([{'employee': []}], status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = EmployeeSerializer(employee) return Response(serializer.data) elif request.method == 'DELETE': employee.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def get(self, request, *args, **kwargs): user_id = kwargs.get('pk') if user_id: emp_obj = Employee.objects.get(pk=user_id) many = False else: emp_obj = Employee.objects.all() many = True emp_ser = EmployeeSerializer(emp_obj, many=many) return Response({'status': 200, 'msg': '查询成功', 'result': emp_ser.data})
def list(request): """List all Employee, or create a new Employee.""" if request.method == 'GET': employee = Employee.objects.all() serializer = EmployeeSerializer(employee, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = EmployeeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, id, format=None): """" GET /api/v1/employee Retrieves a list of employees Pagination can be enabled with parameters: >>>> { 'pagination': true, 'offset': 0, # Default 0 'employees_per_page': 10, # Deafult 10 } Also returns a specific employee if id is specified GET /api/v1/employee/<id> """ # Pagination controls if id: employee = self.get_employee(pk=id) serializer = EmployeeSerializer(employee) return Response(serializer.data) else: offset = 0 employees_per_page = 10 if 'offset' in request.GET: offset = int(request.GET['offset']) if 'employees_per_page' in request.GET: employees_per_page = int(request.GET['employees_per_page']) # Get objects queryset employees = Employee.objects.all().order_by('name') if 'pagination' in request.GET and bool(request.GET['pagination']): # If pagination is active, let's slice the queryset employees = employees[offset:(offset + employees_per_page)] serializer = EmployeeSerializer(employees, many=True) return Response(serializer.data)
def employee_list(request): if request.method == 'GET': print(request) logger.debug("inside get method") employee = Employee.objects.all() firstname = request.GET.get('firstname', None) print(firstname) companyname = request.GET.get('companyname', None) if firstname is not None: logger.debug("firstname is {}".format(firstname)) employee = employee.filter(firstname=firstname) else: if companyname is not None: company = Companyinfo.objects.filter( companyname=companyname)[0] employee = Employee.objects.filter(company=company).count() return HttpResponse(employee) employee_serializer = EmployeeSerializer(employee, many=True) return JsonResponse(employee_serializer.data, safe=False) elif request.method == 'POST': logger.debug("inside post method") employee_data = JSONParser().parse(request) employee_serializer = EmployeeSerializer(data=employee_data) if employee_serializer.is_valid(): employee_serializer.save() return JsonResponse({"message": "valid"}) else: return JsonResponse({"message": "not valid"}) elif request.method == 'DELETE': logger.debug("inside delete method") firstname = request.GET.get('firstname', None) employee = Employee.objects.filter(firstname=firstname) if firstname is not None: employee.delete() return JsonResponse({"message": "deleted successfully"}) else: return JsonResponse({"message": "deletion not successful"}) elif request.method == 'PUT': logger.debug("inside put method") employee_data = JSONParser().parse(request) firstname = employee_data.get("firstname") if firstname is not None: employee = Employee.objects.filter(firstname=firstname) employee.update(**employee_data) return JsonResponse({"message": "updated successful"}) else: return JsonResponse({"message": "update failed"})
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) print("yoso") user = serializer.validated_data token, created = Token.objects.get_or_create(user=user) return Response({ "user": EmployeeSerializer(user, context=self.get_serializer_context()).data, "token": token.key })
def test_employees_serializer(self): """ Esta prueba asegura que todos los empleados agregados en el setUp method existen cuando hacemos la petición a la api /employees python manage.py test <nombre_app> python manage.py test api """ # hit the API endpoint response = self.client.get(reverse("employee-list-drf", kwargs={})) # fetch the data from db expected = Employee.objects.all() serialized = EmployeeSerializer(expected, many=True) self.assertEqual(True, True) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serialized.data)
def post(self, request, *args, **kwargs): emp_data = request.data if not isinstance(emp_data, dict) or emp_data == {}: return Response({'status': 500, 'msg': '数据有误'}) emp_des = EmployeeDeSerializer(data=emp_data) if emp_des.is_valid(): new_emp = emp_des.save() return Response({ 'status': 200, 'msg': '添加单个成功', 'result': EmployeeSerializer(new_emp).data }) else: return Response({ 'status': 500, 'msg': '添加单个失败', 'result': emp_des.errors })
def post(self, request, *args, **kwargs): user_data = request.data print(user_data) '''先进行数据类型判断''' if not isinstance(user_data, dict) or user_data == {}: return Response({ "status": status.HTTP_400_BAD_REQUEST, "message": '你他娘的发歪啦' }) ser = EmployeeDeSerializer(data=user_data) if ser.is_valid(): rst = ser.save() return Response({ "status": status.HTTP_200_OK, "message": '用户成功存进去了', "result": EmployeeSerializer(rst).data }) return Response({ "status": status.HTTP_400_BAD_REQUEST, "message": ser.errors })
def post(self, request, *args, **kwargs): user_data = request.data if not isinstance(user_data, dict) or user_data == {}: return Response({ "status": 501, "msg": "数据有误", }) serializer = EmployeeDeSerializer(data=user_data) print(serializer.is_valid()) if serializer.is_valid(): emp_obj = serializer.save() return Response({ "status": 201, "msg": "用户创建成功", "results": EmployeeSerializer(emp_obj).data }) else: return Response({ "status": 501, "msg": "用户创建失败", "results": serializer.errors })
def contract_employees(request, pk): current_user = request.user # Должность по контракту user_contract_position = get_object_or_404( ContractEmployee, contract_id=pk, employee_id=current_user.id).position if request.method == 'GET': if user_contract_position not in PERMITTED_POSITIONS: return JsonResponse({'message': 'Отказано в доступе'}, status=status.HTTP_403_FORBIDDEN) employees = Employee.objects.raw( CONTRACT_EMPLOYEE_QUERY, { 'contract_id': pk, 'organization_id': current_user.organization_id }) serializer = EmployeeSerializer(employees, many=True) return JsonResponse(serializer.data, safe=False) if request.method == 'POST': if user_contract_position not in PERMITTED_POSITIONS: return JsonResponse({'message': 'Отказано в доступе'}, status=status.HTTP_403_FORBIDDEN) employee_id = request.data['employee_id'] print(employee_id) contract = get_object_or_404(Contract, pk=pk) print(contract) employee = get_object_or_404(Employee, pk=employee_id) print(employee_id) try: ContractEmployee.objects.create(contract=contract, employee=employee, position='SENIOR') return JsonResponse( {'message': 'Пользователь добавлен в контракт'}, status=status.HTTP_200_OK) except IntegrityError as e: return JsonResponse( {'message': 'Пользователь уже существует в данном контракте'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def get(self, requesy, pk): user = User.objects.get(pk=pk) try: client = user.client serializer = ClientSerializer(client) data = serializer.data data["user_type"] = "client" return Response(data) except ObjectDoesNotExist: try: employee = user.employee serializer = EmployeeSerializer(employee) data = serializer.data data["user_type"] = "employee" return Response(data) except ObjectDoesNotExist: owner = user.owner serializer = OwnerSerializer(owner) data = serializer.data data["user_type"] = "owner" return Response(data)