def destroy(self, request, *args, **kwargs): # type: (HttpRequest, *Any, **Any) -> Response try: delete_app_push_msg_by_id(int(kwargs.get('pk'))) except Exception as e: raise exceptions.APIException(e.message) return Response(status=status.HTTP_204_NO_CONTENT)
def change_quotas(self, request, pk=None, **kwargs): site_collection = self.get_object() backend = site_collection.user.tenant.get_backend() serializer_class = self.get_serializer_class() serializer = serializer_class( data=request.data, context={'site_collection': site_collection}) serializer.is_valid(raise_exception=True) new_storage = serializer.validated_data['storage'] old_storage = site_collection.quotas.get( name=models.SiteCollection.Quotas.storage).limit try: backend.site_collections.set_storage( url=site_collection.access_url, storage=new_storage) except SaltStackBackendError as e: raise exceptions.APIException(e.traceback_str) else: site_collection.set_quota_limit( models.SiteCollection.Quotas.storage, new_storage) tenant = site_collection.user.tenant tenant.add_quota_usage(models.SharepointTenant.Quotas.storage, new_storage - old_storage) return response.Response('Storage quota was successfully changed.', status=HTTP_200_OK)
def put(self, request, *args, **kwargs): to_user_id = None card_id = None try: logger.info("Starting function PUT") access_token = self.kwargs['access_token'] logger.info("access token is " + access_token) user = UserProfile.objects.get( profile_id__exact='1069321953161548' ).user # UserProfileView.get_profile(access_token).user logger.info("user found from access token") if "to_user_id" not in request.data or "card_id" not in request.data: raise exceptions.APIException( "to_user_id/card_id not provided") to_user_id = request.data['to_user_id'] card_id = request.data['card_id'] card = CashoutCard.objects.get(pk=int(card_id)) if user not in card.associated_event.admin.all(): raise exceptions.PermissionDenied() to_user = BdayAppUser.objects.get(pk=int(to_user_id)) card.user = to_user card.save() except BdayAppUser.DoesNotExist: raise exceptions.NotFound("to_user_id " + to_user_id + " not found") except CashoutCard.DoesNotExist: raise exceptions.NotFound("card with card id " + card_id + " not found") except Exception as error: CashoutCardView.handle_error(error)
def post(self, request, *args, **kwargs): if not request.user.is_authenticated(): raise PermissionDenied try: # Load offer offer_slug = request.POST.get('offer') offer = PaymentOffer.objects.get(slug=offer_slug) # Load club club_slug = request.POST.get('club') club = None if offer.target == 'club' and club_slug: club = Club.objects.get(pk=club_slug, manager=request.user) # Create client on user if not request.user.paymill_id: request.user.sync_paymill() # Create subscription with client & offer offer.create_subscription(request.POST.get('token'), request.user, club=club) except Exception, e: logger.error('Payment error for %s: %s' % (request.user, e.message)) # Handle paymill errors if isinstance(e.message, dict) and 'error' in e.message: msg = e.message['error'] else: msg = e.message raise exceptions.APIException(msg)
def perform_create(self, serializer): user = serializer.validated_data['user'] template = serializer.validated_data['template'] backend = user.tenant.get_backend() if user.tenant.state != models.SharepointTenant.States.ONLINE: raise IncorrectStateException( "Tenant must be in stable state to perform site collection creation" ) try: storage = serializer.validated_data.pop('storage') backend_site = backend.site_collections.create( admin_id=user.admin_id, template_code=template.code, site_url=serializer.validated_data['site_url'], name=serializer.validated_data['name'], description=serializer.validated_data['description'], storage=storage) except SaltStackBackendError as e: raise exceptions.APIException(e.traceback_str) else: site_collection = serializer.save() site_collection.access_url = backend_site.url site_collection.save() site_collection.set_quota_limit(site_collection.Quotas.storage, storage) user.tenant.add_quota_usage(models.SharepointTenant.Quotas.storage, storage)
def create(self, validated_data): person = Person(**validated_data) try: person.save() except Exception as e: raise exceptions.APIException() return person
def put(self, request, publisher_id, dataset_id): publisher = Publisher.objects.get(pk=publisher_id) source_url = request.data.get('source_url', None) # TODO: call package_update to update source_url for registry as well # - 2017-02-20 if not source_url: raise exceptions.APIException(detail="no source_url provided") dataset = Dataset.objects.get(id=dataset_id) dataset.date_updated = datetime.now() dataset.source_url = source_url dataset.save() # get all ready to publish organisations organisations = Organisation.objects.filter(ready_to_publish=True, publisher=publisher) non_r2p_organisations = Organisation.objects.filter( ready_to_publish=False, publisher=publisher) # update the affected organisations flags organisations.update( published=True, modified=False, ready_to_publish=True, last_updated_datetime=datetime.now().isoformat(' ')) non_r2p_organisations.update(published=False) # return Dataset object serializer = DatasetSerializer(dataset, context={'request': request}) return Response(serializer.data)
def create(self, request, *args, **kwargs): if 'username' in request.data: request.data['username'] = request.data['username'].lower() serializer = super().get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() user.set_password(request.data['password']) user.save() if not user.uuid or not user.email: raise exceptions.APIException(detail="No data to send email.") token = TokenService.create(user.uuid, Token.TYPE_USER_CONFIRM, timedelta(hours=1)).get_token() EmailService().send_mail('confirm_account.html', 'Welcome to Cooksel', [user.email], { 'token': token, 'request': request, }) headers = super().get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def is_allowed_version(self, version): print(111) print(version) print(self.allowed_versions) if version in self.allowed_versions: return True raise exceptions.APIException(detail={'code': -1, 'msg': '错误的版本号'})
def deactivate(request, id): id_institution = request.user.instit_id id_matriz = search_matriz(id_institution) user_id = request.user.id if not verify_permission(143, user_id): raise exceptions.PermissionDenied( 'Você não tem permissões para realizar esta operação.') product = Produtos.objects.filter(id=id, id_matriz=id_matriz).first() product_item = ProdItens.objects.filter( id_produtos=product.id, id_matriz=id_matriz).first() if not product: raise exceptions.NotFound('Registro não encontrado, tente novamente.') try: product.ativo = 1 product.save() product_item.ativo = 1 product_item.save() produtos = Produtos.objects.filter( id_matriz=id_matriz).order_by('descr').order_by('-ativo') produtos_serialized = ProdutoSerializer(produtos, many=True) return Response(produtos_serialized.data) except: raise exceptions.APIException( 'Não foi possível realizar a operação, tente novamente.')
def register(request): data = request.data new_data = data.copy() if (data['password'] != data['password_confirm']): raise exceptions.APIException('Passwords do not match') if data['role'] == 'Pharmacy Worker': new_data['medical_license'] = uri_to_img(data['role'], data['medical_license'], data['username']) serializer = PharmacyWorkerSerializer(data=new_data) elif data['role'] == 'Owner': new_data['business_permit'] = uri_to_img(data['role'], data['business_permit'], data['username']) serializer = OwnerSerializer(data=new_data) elif data['role'] == 'Customer': new_data['valid_id1'] = uri_to_img(data['role'], data['valid_id1'], data['username']) print("CUSTOMER VRO") serializer = CustomerSerializer(data=new_data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data)
def activate(request, id): id_institution = request.user.instit_id id_matriz = search_matriz(id_institution) user_id = request.user.id if not verify_permission(144, user_id): raise exceptions.PermissionDenied( 'Você não tem permissões para realizar esta operação.') product = Produtos.objects.filter(id=id, id_matriz=id_matriz).first() product_item = ProdItens.objects.filter( id_produtos=product.id, id_matriz=id_matriz).first() if not product: raise exceptions.NotFound('Registro não encontrado, tente novamente.') try: product.ativo = 2 product.save() product_item.ativo = 2 product_item.save() return Response({'detail': 'O registro do produto foi ativado com sucesso.'}) except: raise exceptions.APIException( 'Não foi possível realizar a operação, tente novamente.')
def create(request): id_institution = request.user.instit_id id_matriz = search_matriz(id_institution) id_user = request.user.id if not verify_permission(111, id_user): raise exceptions.PermissionDenied( 'Você não tem permissões para realizar esta operação.') try: fabricante = Fabpro(instit=id_matriz, marca=request.data.get('marca'), fabr=request.data.get('fabr'), data_criacao=timezone.now()) fabricante.save() fabricantes = Fabpro.objects.filter(instit=id_matriz) fabricantes_serialized = FabricanteProdutoSerializer(fabricantes, many=True) return Response(fabricantes_serialized.data) except: raise exceptions.APIException( 'Não foi possível cadastrar o fabricante, tente novamente')
def update(request, id): id_institution = request.user.instit_id id_matriz = search_matriz(id_institution) id_user = request.user.id if not verify_permission(141, id_user): raise exceptions.PermissionDenied( 'Você não tem permissões para realizar esta operação.') try: fabricante = Fabpro.objects.filter(instit=id_matriz, id=id).first() fabricante.marca = request.data.get('marca') fabricante.fabr = request.data.get('fabr') fabricante.save() fabricantes = Fabpro.objects.filter(instit=id_matriz) fabricantes_serialized = FabricanteProdutoSerializer(fabricantes, many=True) return Response(fabricantes_serialized.data) except: raise exceptions.APIException( 'Não foi possível atualizar o registro de fabricante, tente novamente.' )
def post(self, request): order = Order.objects.filter(transaction_id=request.data['source']).first() if not order: raise exceptions.APIException('Order not found!') order.complete = 1 order.save() # Admin Email send_mail( subject='An Order has been completed', message='Order #' + str(order.id) + 'with a total of $' + str(order.admin_revenue) + ' has been completed!', from_email='*****@*****.**', recipient_list=['*****@*****.**','*****@*****.**'] ) send_mail( subject='An Order has been completed', message='You earned $' + str(order.ambassador_revenue) + ' from the link #' + order.code, from_email='*****@*****.**', recipient_list=[order.ambassador_email,"*****@*****.**"] ) return Response({ 'message': 'success' })
def deplay_lesson_env(request): try: lesson_hash = request.data['lesson_hash'] except Exception as e: raise exceptions.ParseError(error.INVALID_PARAMS) try: lesson = Lesson.objects.get(pk=lesson_hash) except Lesson.DoesNotExist as e: raise exceptions.NotFound(error.LESSON_NOT_EXIST) try: env_handler = EnvHandler(request.user) except MsgException as e: raise exceptions.NotFound(e.message) try: env = env_handler.delay(lesson) except MsgException as e: raise exceptions.PermissionDenied(e.message) except Exception as e: raise exceptions.APIException(error.DELAY_LESSONENV_ERROR) data = { 'destroy_time': env.destroy_time, 'remain_seconds': get_remain_seconds(env.destroy_time), } return Response(data)
def get_error_trace(self, instance): report_id = self.context['request'].query_params.get('report') # Get the most relevant mark association if report_id: mark_report = MarkUnsafeReport.objects.filter( mark=instance, report_id=report_id).first() else: mark_report = MarkUnsafeReport.objects.filter( mark=instance).order_by('-result').first() if not mark_report: raise exceptions.APIException( "The mark don't have any associations") # Trying to get converted report's error trace converted = ConvertedTrace.objects.filter( unsafeconvertioncache__unsafe=mark_report.report, function=instance.function).first() if not converted: # If not found convert error trace and save the convertion cache with open(mark_report.report.error_trace.path, mode='r', encoding='utf-8') as fp: error_trace = json.load(fp) converted = convert_error_trace(error_trace, instance.function) UnsafeConvertionCache.objects.create( unsafe_id=mark_report.report_id, converted_id=converted.id) with open(converted.file.path, mode='r', encoding='utf-8') as fp: # Return converted error trace return json.load(fp)
def create_env(user_id, team_id, lesson_hash, backend_admin): try: user = User.objects.get(pk=user_id) except User.DoesNotExist as e: raise exceptions.NotFound(error.USER_NOT_EXIST) team = get_team(team_id) try: lesson = Lesson.objects.get(pk=lesson_hash) except Lesson.DoesNotExist as e: raise exceptions.NotFound(error.LESSON_NOT_EXIST) executor = get_executor(user_id, team_id, lesson_hash, backend_admin) try: env_handler = EnvHandler(user, backend_admin=backend_admin, team=team, executor=executor) except MsgException as e: raise exceptions.NotFound(e.message) try: lesson_env = env_handler.create(lesson) except MsgException as e: raise exceptions.PermissionDenied(e.message) except PoolFullException as e: raise exceptions.PermissionDenied(json.dumps(e.executor_info), code='PoolFull') except Exception as e: logger.error('create lessonenv error[lesson_hash=%s, user_id=%s]: %s' % (lesson_hash, user.id, e)) raise exceptions.APIException(error.CREATE_LESSON_ENV_ERROR) return lesson_env
def get_users_company(request): if request.user.is_admin: return Response(data=user_service.get_users_by_company(request.user)) elif request.user.is_gas_station_admin: return Response(data=user_service.get_users_by_station(request.user)) else: raise exceptions.APIException("User not allowed")
def patch(self, request, *args, **kwargs): check_user = User.objects.filter(id=kwargs['pk']) if check_user.exists(): user = check_user.last() if self.request.data.get('first_name') is not None: user.first_name = self.request.data.get('first_name') if self.request.data.get('last_name') is not None: user.last_name = self.request.data.get('last_name') user.save() userProfile = UserProfile.objects.get(user_id=user.id) profileObj = self.request.data.get('profile') state = State.objects.filter(id=profileObj['state']['id']) userProfile.address1 = profileObj['address1'] userProfile.address2 = profileObj['address2'] userProfile.city = profileObj['city'] userProfile.state = state.last() userProfile.country = profileObj['country'] userProfile.contact_number = profileObj['contact_number'] userProfile.pincode = profileObj['pincode'] userProfile.role = profileObj['role'] userProfile.save() return Response('updated') else: error = 'The requested resource is not found' raise exceptions.APIException(error)
def exception_handler(exc, context): # Convert Django exceptions (from DRF). if isinstance(exc, Http404): exc = exceptions.NotFound() elif isinstance(exc, PermissionDenied): exc = exceptions.PermissionDenied() elif not isinstance(exc, exceptions.APIException): # Fallback handler to convert remaining exceptions to API exception. logger.exception(exc) exc = exceptions.APIException(exc) request = context['request'] response = drf_exception_handler(exc, context) data = response.data problem_title = getattr(exc, 'title', exc.default_detail) problem_status = response.status_code problem_code = getattr(exc, 'code', exc.default_code) problem_type = reverse('drf_problems:error-documentation', kwargs={'code': problem_code}, request=request) if isinstance(data, dict): data['title'] = problem_title data['status'] = problem_status data['type'] = problem_type else: data = dict(errors=response.data, title=problem_title, status=problem_status, type=problem_type) try: if request.accepted_renderer.format == 'json': response.content_type = 'application/problem+json' except AttributeError: pass response.data = data return response
def signup(request): data = request.data if data['password'] != data["password_confirm"]: raise exceptions.APIException("le mot de passe ne convient pas") serializer = UsersSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data)
def perform_create(self, serializer): try: with transaction.atomic(): serializer.save() except Exception as e: print(e) raise exceptions.APIException( 'Error while reading file. Please verify uploaded file')
def validate(self, data): business_id = data.get("business_id", "") if business_id: return business_id else: mes = "Please Enter Business Id." # Message if email not registered. raise exceptions.APIException( mes) # Call message if email not registered.
def post(self, request): data = request.data if data['price'] < 0: raise exceptions.APIException('Price is negative') if data['quantity'] < 0: raise exceptions.APIException('Quantity is negative') new_data = data.copy() new_data['product_img'] = uri_to_img(data['name'], data['product_img']) serializer = ProductSerializer(data=new_data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
def register(request): data = request.data if data["password"] != data["password_confirm"]: raise exceptions.APIException("Passwords do not match!") serializer = UserSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data)
def retrieve(self, request, *args, **kwargs): try: res = es.get(index="test_12", doc_type="one", id=kwargs["pk"]) except NotFoundError as exc: raise exceptions.NotFound("Document {} was not found in Type one of Index test_12".format(kwargs["pk"])) except Exception as exc: raise exceptions.APIException("内部错误, 错误类型:{}".format(type(exc))) return Response(res)
def list(self, request, *args, **kwargs): offset = request.query_params.get("offset", 0) limit = request.query_params.get("limit", 10) try: res = es.search(index="test_12", doc_type="one", size=limit, from_=offset) except Exception as exc: raise exceptions.APIException("内部错误,错误类型: {}".format(type(exc))) return Response(res["hits"])
def get_settings_groups(group_setting_name): groupnames = getattr(settings, group_setting_name, None) if groupnames is None: raise exceptions.APIException( detail=f'{group_setting_name} is unset in config') if isinstance(groupnames, str): groupnames = (groupnames, ) return groupnames
def list(self, request, *args, **kwargs): page = int(request.query_params.get("page", 1)) page_size = int(request.query_params.get("page_size", 10)) try: res = es.search(index=deleted_data_index, doc_type="deleted-data", size=page_size, from_=(page-1)*page_size) except Exception as exc: raise exceptions.APIException("内部错误,错误类型: {}".format(type(exc))) return Response(res["hits"])