def validate_api_call(response, exceptions):
    if (response.status_code < 200 or response.status_code > 299
        ) and response.status_code not in exceptions:
        logger.critical(
            "status_code={} message= WS URI '{}' returned a status code '{}' which was not in the "
            "exceptions list.".format(response.status_code,
                                      response.request.url,
                                      response.status_code))
        raise InternalError(
            "Shared Ride Vans Webservice Status Code Error. Status Code {}".
            format(response.status_code))
示例#2
0
    def delete(self, *args, **kwargs):
        for i in self.contactregistry_set.all():
            try:
                apps.epp_client.delete_contact(i.registry_contact_id,
                                               i.registry_id)
            except grpc.RpcError as rpc_error:
                error = rpc_error.details()
                raise InternalError(error)
            i.delete()

        as207960_utils.models.delete_resource(self.resource_id)
        super().delete(*args, **kwargs)
示例#3
0
    def test_authentication_server_exception(self, logger_mock, get_user_mock):
        """tests internal server exception"""

        get_user_mock.return_value.DoesNotExist = ObjectDoesNotExist
        get_user_mock.return_value.objects.get.side_effect = InternalError(
            'internal server exception')
        request = self.req_factory.get('/', {'token': self.token})
        # trick because of: AttributeError: 'WSGIRequest' object has no attribute 'query_params'
        request = APIView().initialize_request(request)
        with self.assertRaisesMessage(InternalServerException,
                                      'Hmm...we do not support that yet'):
            self.auth_obj.authenticate(request)
        get_user_mock.assert_called_once()
        logger_mock.assert_called_once()
示例#4
0
文件: log.py 项目: Althis/bagtrekkin
 def create(user, luggage, flight=None, status=LOG_STATUSES[2][0]):
     '''Create a new Log based on user, using luggage and flight if any'''
     if not luggage.pk:
         raise InternalError('Luggage can\'t be saved... Please try again.')
     if not flight:
         if not user.employee.current_flight:
             raise FieldError(
                 'Missing current_flight for current Employee. '
                 'Please set your current_flight first.')
         flight = user.employee.current_flight
     datetime = timezone.now()
     Log(datetime=datetime,
         employee=user.employee,
         luggage=luggage,
         flight=flight,
         status=status).save()
    def _get_database_credentials_from_vault(self):
        client = self._get_hvac_client()

        if not client.is_authenticated():
            raise RuntimeError("Not authenticated to Vault.")

        settings_dict = self.settings_dict

        vault_role_name = settings_dict.get('VAULT_ROLE_NAME', None)
        vault_db_mount_point = settings_dict.get(
            'VAULT_DB_MOUNT_POINT', self.DEFAULT_VAULT_DB_MOUNT_POINT)
        if vault_db_mount_point is None:
            vault_db_mount_point = self.DEFAULT_VAULT_DB_MOUNT_POINT

        if vault_role_name is None:
            raise ImproperlyConfigured(
                "settings.DATABASES is improperly configured. "
                "Please supply a Vault role name in VAULT_ROLE_NAME.")

        params = {
            'name': vault_role_name,
            'mount_point': vault_db_mount_point,
        }

        try:
            creds = client.secrets.database.generate_credentials(**params)
        except requests.exceptions.MissingSchema as e:
            exc_msg = e.args[0]
            if exc_msg.startswith('Invalid URL') and ('No schema supplied'
                                                      in exc_msg):
                raise ImproperlyConfigured(
                    "settings.DATABASES is improperly configured. "
                    "Please supply a valid Vault URL in VAULT_ADDR. "
                    "Did you forget your protocol schema? "
                    "e.g. 'http', 'https'")
            else:
                # If we don't know what happened,
                # re-raise the original exception
                raise e
        except hvac.exceptions.Forbidden as e:
            msg = e.args[0]
            raise InternalError(msg)
        except hvac.exceptions.VaultError as e:
            msg = e.args[0]
            raise OperationalError(msg)

        return creds
def __handle_file_upload(request_files):
    response = dbs_api.batch_overwrite(
        {'capita_list_file': request_files['capita_list_file'].file})

    if response.status_code == 201:
        return

    elif response.status_code == 400:
        response_text = json.loads(response.text)
        raise ValidationError(response_text)

    else:

        try:
            response_text = json.loads(response.text)
        except json.JSONDecodeError:
            response_text = 'No response text to show.'

        raise InternalError(
            'The DBS API returned a %i status code. Response text: %s' %
            (response.status_code, response_text))
示例#7
0
    def can_delete(self):
        if self.domains_registrant.count() or self.domains_admin.count() or \
                self.domains_tech.count() or self.domains_billing.count() or \
                self.domain_registration_orders_registrant.count() or self.domain_registration_orders_admin.count() or \
                self.domain_registration_orders_tech.count() or self.domain_registration_orders_billing.count() or \
                self.domain_transfer_orders_registrant.count() or self.domain_transfer_orders_admin.count() or \
                self.domain_transfer_orders_tech.count() or self.domain_transfer_orders_billing.count():
            return False

        for i in self.contactregistry_set.all():
            try:
                contact_data = apps.epp_client.get_contact(
                    i.registry_contact_id, i.registry_id)
            except grpc.RpcError as rpc_error:
                error = rpc_error.details()
                raise InternalError(error)

            if apps.epp_api.contact_pb2.Linked in contact_data.statuses:
                return False

        return True
示例#8
0
def transfer_narratives(request, experience_id):
    from_experience = get_object_or_404(Experience, pk=experience_id)

    if request.user not in from_experience.explorers.all():
        raise PermissionDenied

    other_experiences = request.user.experiences.exclude(pk=experience_id)
    NewExperienceForm = modelform_factory(Experience, form=ExperienceForm,
            fields=('title',))

    if request.method == 'POST':
        if request.POST.get('new_experience'):
            to_experience = NewExperienceForm(request.POST, request=request,
                    author=request.user).save()
        elif request.POST.get('to_experience_id'):
            to_experience = get_object_or_404(Experience, pk=request.POST.get('to_experience_id'))

        if request.user not in to_experience.explorers.all():
            raise PermissionDenied

        action_choices = {index: value for index, value in TRANSFER_ACTION_CHOICES[1:]}

        num_copies = 0
        num_transfers = 0
        for narrative_id, action_index in zip(request.POST.getlist('narrative_ids'), request.POST.getlist('potential_actions')):
            if action_index:
                action = action_choices[int(action_index)]
                narrative = get_object_or_404(Narrative, pk=int(narrative_id))

                if narrative not in from_experience.narratives.all():
                    raise PermissionDenied

                if action == 'Transfer':
                    try:
                        to_experience.narratives.add(narrative)
                        num_transfers += 1
                    except:
                        raise InternalError('Sorry, something went wrong')
                elif action == 'Copy':
                    try:
                        # Fairly obscure way of copying the object seemingly demanded by Django
                        narrative.pk = None
                        narrative.experience = to_experience
                        narrative.save()
                        num_copies += 1
                    except:
                        raise InternalError('Sorry, something went wrong')
                
        if num_copies + num_transfers > 0:
            msg = 'Successfully '
            if num_copies:
                msg += 'copied {0} narrative{1} '.format(num_copies, '' if num_copies == 1 else 's')
                if num_transfers:
                    msg += 'and '
            if num_transfers:
                msg += 'transferred {0} narrative{1} '.format(num_transfers, '' if num_transfers == 1 else 's')
            msg += 'to {0}'.format(to_experience)
            messages.success(request, _(msg))
            return redirect(reverse('experience', args=(to_experience.id,)))

    narrative_forms = [NarrativeTransferForm(instance=n) for n in from_experience.narratives.all()]
    context = {
        'experience': from_experience,
        'other_experiences': other_experiences,
        'narrative_forms': narrative_forms,
        'new_experience_form': NewExperienceForm(),
    }
    return render(request, 'experiences/transfer_narratives.html', context)