def wrapper(self, request, *args, **kwargs): try: request.board = Board.objects.get(uuid=kwargs.get("board_id", None)) return fn(self, request, *args, **kwargs) except (Board.DoesNotExist, ValidationError): return ErrorResponse(status=HTTPStatus.NOT_FOUND) except Board.MultipleObjectsReturned: return ErrorResponse(status=HTTPStatus.BAD_GATEWAY)
def wrap(request, *args, **kwargs): data = json.loads(request.body) is_valid = schema.is_valid(data) if is_valid is False: return ErrorResponse(status=HTTPStatus.BAD_REQUEST) request.json_data = data return view_func(request, *args, **kwargs)
def get(self, request, poke_type): try: result_json = pokemon_filter_service.get_pokemon_data_by_type( poke_type) return Response(result_json) except Exception as e: return ErrorResponse(traceback.format_exc())
def delete(self, request, poke_number, poke_evo_number): try: result_json = pokemon_evos_service.delete_evos_pokemon_data( poke_number, poke_evo_number) return Response(result_json) except Exception as e: return ErrorResponse(traceback.format_exc())
def post(self, request): userId = request.POST.get('userId') if is_none_or_empty(userId): return EmptyResponse() user = userId2user(userId) if user: if scheduleOption.exist_schedule_for_semester(user): return ErrorResponse('本学期课表已经存在或者正在导入中') scheduleOption.import_schedule(user) # 导入课表 if scheduleOption.exist_schedule_for_semester(user): # 检查课表是否导入成功 return SuccessResponse('导入课表成功') else: return ErrorResponse('导入课表失败') else: return UserIdErrorResponse()
def get(self, request): try: params = request.GET assert 'customer_id' in params and params[ 'customer_id'] != '', "parameter customer_id not found::404" customer_id = params['customer_id'] customer = checkIsExists(Customers, id=int(customer_id)) assert customer, "customer not found::404" carts = Carts.objects.filter(customer_id=customer_id) data = getPaginate(request, carts, pageQueryName='page', sizeQueryName='page_size') return SuccessResponse({ 'data': CartSerializer(data['data'], many=True).data, 'meta': data['meta'] }) except AssertionError as error: return AssertionErrorResponse(str(error)) except Exception as error: print(error) return ErrorResponse("Internal Server Error", 500)
def post(self, request): try: data = request.data customer = checkIsExists(Customers, id=data['customer_id']) product = checkIsExists(Products, id=data['product_id']) assert customer, "customer not found::404" assert product, "product not found::404" already_exist = checkIsExists(Carts, customer_id=customer.id, product_id=product.id) if already_exist: varian_exist = json.loads(already_exist.varian) varian_data = data['varian'] # check if data already exist with the same varian if self.checkVarianExist(varian_data, varian_exist): current_quantity = already_exist.quantity already_exist.quantity += current_quantity already_exist.save() else: self.saveData(data, product) else: self.saveData(data, product) return SuccessResponse({'message': 'data successfully added!'}) except AssertionError as error: return AssertionErrorResponse(str(error)) except Exception as error: print(error) return ErrorResponse("Internal Server Error", 500)
def post(self, request): userId = request.POST.get('userId') if is_none_or_empty(userId): return EmptyResponse() user = userId2user(userId) if user: try: userinfo = UserInfo.objects.get(username=user.username) except UserInfo.DoesNotExist: userinfo = None if userinfo: data = { 'username': userinfo.username, 'name': userinfo.name, 'gender': userinfo.gender, 'grade': userinfo.grade, 'college': userinfo.college, 'professional': userinfo.professional, 'classname': userinfo.classname, 'dormitory': userinfo.dormitory, 'number': userinfo.number } return SuccessResponse('获取用户数据成功', data) return ErrorResponse('暂时没有当前用户的信息') else: return UserIdErrorResponse()
def get(self, request, poke_number): try: # poke_number = request.query_params.get("poke_number") result_json = pokemon_service.get_pokemon_data(poke_number) return Response(result_json) except Exception as e: return ErrorResponse(traceback.format_exc())
def post(self, request, poke_number): try: poke_evo_number = request.data.get("poke_evo_number") result_json = pokemon_evos_service.create_evos_pokemon_data( poke_number, poke_evo_number) return Response(result_json) except Exception as e: return ErrorResponse(traceback.format_exc())
def put(self, request, poke_number): try: poke_name = request.data.get("poke_name") poke_types = request.data.get("poke_types") result_json = pokemon_service.update_pokemon_data( poke_number, poke_name, poke_types) return Response(result_json) except Exception as e: return ErrorResponse(traceback.format_exc())
def signup(request): user_info = request.json_data if User.objects.filter(email=user_info["email"]).exists(): return ErrorResponse(status=HTTPStatus.CONFLICT) new_user = User() new_user.email = user_info["email"] new_user.username = user_info["email"] new_user.set_password(user_info["password"]) new_user.save() user = authenticate(username=new_user.email, password=user_info["password"]) if user is not None: login(request, user) response = {"email": new_user.email} return SuccessResponse(response, status=HTTPStatus.CREATED) else: return ErrorResponse(status=HTTPStatus.BAD_REQUEST)
def signin(request): user_info = request.json_data user = authenticate(username=user_info["email"], password=user_info["password"]) if user is not None: login(request, user) response = {"email": user.email} return SuccessResponse(response) else: return ErrorResponse(status=HTTPStatus.UNAUTHORIZED)
def post(self, request): userId = request.POST.get('userId') if is_none_or_empty(userId): return EmptyResponse() user = userId2user(userId) if user: has_schedule = scheduleOption.exist_schedule_for_semester(user) if has_schedule: return SuccessResponse("本学期已存在课表哦") else: return ErrorResponse('本学期没有导入课表哦', 2) else: return UserIdErrorResponse()
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): user = serializer.user token, _ = Token.objects.get_or_create(user=user) return Response( data=TokenSerializer(token).data, status=status.HTTP_200_OK, ) else: return ErrorResponse( data=serializer.errors, status=status.HTTP_400_BAD_REQUEST, )
def post(self, request): userId = request.POST.get('userId') if is_none_or_empty(userId): return EmptyResponse() user = userId2user(userId) if user: schedules = scheduleOption.schedule_for_tomorrow(user) if schedules: return SuccessWeekResponse('明日课表获取成功', current_week(), schedules) else: return ErrorResponse('明天没有课哦', 2) else: return UserIdErrorResponse()
def post(self, request): userId = request.POST.get('userId') love = request.POST.get('love') if is_none_or_empty(userId, love): return EmptyResponse() user = userId2user(userId) if not user: return UserIdErrorResponse() userWeChatInfo = userId2UserWeChatInfo(userId) if not userWeChatInfo: # 当前用户未授权用户 return ErrorResponse('当前用户未授权微信信息', 2) love = Love.objects.create( user=user, user_weChat_info=userWeChatInfo, content=love, ) return SuccessResponse('发布表白成功,请等待审核哦!', love.id)
def post(self, request): userId = request.POST.get('userId') username = request.POST.get('username') password = request.POST.get('password') if is_none_or_empty(userId, username, password): return EmptyResponse() # 检测用户名和密码是否正确 if userOption.check_username_and_password(username, password): user = userId2user(userId) if user: user.is_active = 1 user.username = username user.password = password user.save() return SuccessResponse('当前用户已激活') return UserIdErrorResponse() else: return ErrorResponse('用户名或密码错误')
def post(self, request): userId = request.POST.get('userId') week = request.POST.get('week') if is_none_or_empty(userId): return EmptyResponse() if is_none_or_empty(week) or int(week) < 0: week = current_week() user = userId2user(userId) if user: schedules = scheduleOption.schedule_for_week(user, week) if schedules: return SuccessWeekResponse('课表获取成功', week, schedules) else: return ErrorResponse('这周没有课哦', 2) else: return UserIdErrorResponse()
def post(self, request): userId = request.POST.get('userId') if is_none_or_empty(userId): return EmptyResponse() user = userId2user(userId) if user: try: user_wechat_info = UserWeChatInfo.objects.get(user=user) except UserWeChatInfo.DoesNotExist: user_wechat_info = None if user_wechat_info: data = { 'avatarUrl': user_wechat_info.avatarUrl, 'gender': user_wechat_info.gender } return SuccessResponse('获取用户数据成功', data) return ErrorResponse('暂时没有当前用户的信息') else: return UserIdErrorResponse()
def post(self, request): try: data = request.data serializer = CustomerSerializer(data=data) if serializer.is_valid(): saved = serializer.save() saved.password = generateHash(data['password']) saved.save() include_address = False address_saved = None if 'address' in data and data['address'] != {}: address = data['address'] if not isinstance(address, dict): temp = json.dumps(address) address = json.loads(temp) address_serializer = CustomerAddressSerializer( data=address) if address_serializer.is_valid(): address_saved = address_serializer.save() address_saved.default = True address_saved.customer_id = saved.id address_saved.save() include_address = True resp = { "message": "data successfully added!", "data": CustomerSerializer(saved, many=False).data } if include_address: resp['address'] = CustomerAddressSerializer( address_saved, many=False).data return SuccessResponse(resp) else: raise except AssertionError as error: return AssertionErrorResponse(str(error)) except: return ErrorResponse("Bad Request")
def post(self, request): try: data = request.data customer_id = data['customer_id'] customer = checkIsExists(Customers, id=customer_id) assert customer, "customer_id not found::404" serializer = SellerSerializer(data=data) if serializer.is_valid(): saved = serializer.save() customer.is_seller = True customer.save() return SuccessResponse({"message": "data successfully added!"}) else: raise except AssertionError as error: return AssertionErrorResponse(str(error)) except: return ErrorResponse("Bad Request")
def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # Check old password if not self.object.check_password( serializer.data.get("old_password")): return Response({"old_password": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST) # set_password also hashes the password that the user will get self.object.set_password(serializer.data.get("new_password")) self.object.save() response = { 'status': 'success', 'message': 'Password updated successfully', } return Response(response, status=status.HTTP_200_OK) return ErrorResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def wrapper(request, *args, **kwargs): if not request.user.is_authenticated: return ErrorResponse(status=HTTPStatus.UNAUTHORIZED) else: return fn(request, *args, **kwargs)
def post(self, request): try: data = request.data merchant = checkIsExists(Merchants, id=data['merchant_id']) category = checkIsExists(Categories, id=data['category_id']) assert merchant, "merchant_id is not found::404" assert category, "caregory_id is not found::404" product = None product_spec = [] product_tags = [] try: product = Products.objects.create( merchant_id=data['merchant_id'], name=data['name'], description=data['description'], price=data['price'], stocks=data['stocks'], category_id=data['category_id'], varian=json.dumps(data['varian']), media=json.dumps(data['media'])) if 'specifications' in data: specifications = data['specifications'] if not isinstance(specifications, list): specifications = json.loads(specifications) for spec in specifications: try: temp = ProductSpecifications.objects.create( product_id=product.id, name=spec['name'], value=spec['value']) product_spec.append(temp) except: pass if 'tags' in data: tags = data['tags'] if not isinstance(tags, list): tags = json.loads(tags) for tag in tags: try: temp = ProductTags.objects.create( product_id=product.id, # name = tag['name'] name=tag) product_tags.append(temp) except: pass return SuccessResponse( {"message": "data successfully created"}) except Exception as error: if product != None: product.delete() if len(product_spec) > 0: for i in product_spec: i.delete() if len(product_tags) > 0: for i in product_tags: i.delete() print(str(error)) raise AssertionError("error while submitting data::400") except AssertionError as error: return AssertionErrorResponse(str(error)) except: return ErrorResponse("BadRequest")
def me(request): if request.user.is_authenticated: return SuccessResponse({"email": request.user.email}) else: return ErrorResponse(status=HTTPStatus.UNAUTHORIZED)