Python http.HTTPStatus.CONFLICT Examples

The following are 10 code examples of http.HTTPStatus.CONFLICT(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module http.HTTPStatus , or try the search function .
Example #1
Source File: directory.py    From loaner with Apache License 2.0 5 votes vote down vote up
def insert_role(self, name=_ROLE_NAME, customer_id='my_customer'):
    """Creates and inserts a new GSuite Admin Role.

    Args:
      name: str, the name of the new GSuite Admin Role.
      customer_id: str, the G Suite customer ID to insert the role into.

    Returns:
      A dictionary object representing the new GSuite Admin Role.
          https://developers.google.com/admin-sdk/directory/v1/reference/roles

    Raises:
      AlreadyExistsError: when the role with the provided name already exists.
      ForbiddenError: when authorization fails.
      InsertionError: when creation fails (e.g. failed to authenticate, improper
          scopes, etc).
    """
    try:
      return self._client.roles().insert(
          customer=customer_id,
          body={
              'roleName': name,
              'rolePrivileges': _ROLE_PRIVILEGES,
              'roleDescription': _ROLE_DESCRIPTION,
              'isSystemRole': False,
              'isSuperAdminRole': False,
          },
      ).execute()
    except errors.HttpError as err:
      status = err.resp.status

      if (status == http_status.CONFLICT or
          status == http_status.INTERNAL_SERVER_ERROR):
        raise AlreadyExistsError(
            'role with name {!r} already exists'.format(name))

      if status == http_status.FORBIDDEN:
        raise ForbiddenError(_FORBIDDEN_ERROR_MSG)

      logging.error(_INSERT_ROLE_ERROR_MSG, name, err)
      raise InsertionError(_INSERT_ROLE_ERROR_MSG % (name, err)) 
Example #2
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def user_exists(self) -> web.Response:
        return web.json_response({
            "error": "There is already a client with the user ID of that token",
            "errcode": "user_exists",
        }, status=HTTPStatus.CONFLICT) 
Example #3
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def plugin_exists(self) -> web.Response:
        return web.json_response({
            "error": "A plugin with the same ID as the uploaded plugin already exists",
            "errcode": "plugin_exists"
        }, status=HTTPStatus.CONFLICT) 
Example #4
Source File: test_tag_common.py    From amundsenmetadatalibrary with Apache License 2.0 5 votes vote down vote up
def test_block_tag_on_reserved_badge_value(self) -> None:
        self.app.config['WHITELIST_BADGES'] = [BADGE_NAME]

        mock_proxy = MagicMock()

        tag_common = TagCommon(client=mock_proxy)
        response = tag_common.put(id='',
                                  resource_type=ResourceType.Dashboard,
                                  tag=BADGE_NAME,
                                  tag_type='default')

        self.assertEqual(response[1], HTTPStatus.CONFLICT) 
Example #5
Source File: test_table_badge_api.py    From amundsenmetadatalibrary with Apache License 2.0 5 votes vote down vote up
def test_block_tag_on_reserved_badge_value(self) -> None:
        self.app.config['WHITELIST_BADGES'] = [BADGE_NAME]
        response = self.app.test_client().put(f'/table/{TABLE_NAME}/tag/{BADGE_NAME}')

        self.assertEqual(response.status_code, HTTPStatus.CONFLICT) 
Example #6
Source File: google.py    From cloudstorage with MIT License 5 votes vote down vote up
def delete_container(self, container: Container) -> None:
        bucket = self._get_bucket(container.name)

        try:
            bucket.delete()
        except Conflict as err:
            if err.code == HTTPStatus.CONFLICT:
                raise IsNotEmptyError(messages.CONTAINER_NOT_EMPTY % bucket.name)
            raise 
Example #7
Source File: rackspace.py    From cloudstorage with MIT License 5 votes vote down vote up
def delete_container(self, container: Container) -> None:
        try:
            self.object_store.delete_container(container.name)
        except ResourceNotFound:
            raise NotFoundError(messages.CONTAINER_NOT_FOUND % container.name)
        except HttpException as err:
            if err.status_code == HTTPStatus.CONFLICT:
                raise IsNotEmptyError(messages.CONTAINER_NOT_EMPTY % container.name)
            raise CloudStorageError(err.details) 
Example #8
Source File: test_skill_dialog.py    From botbuilder-python with MIT License 4 votes vote down vote up
def test_should_not_intercept_oauth_cards_for_bad_request(self):
        connection_name = "connectionName"
        first_response = ExpectedReplies(
            activities=[
                SkillDialogTests.create_oauth_card_attachment_activity("https://test")
            ]
        )

        sequence = 0

        async def post_return():
            nonlocal sequence
            if sequence == 0:
                result = InvokeResponse(body=first_response, status=HTTPStatus.OK)
            else:
                result = InvokeResponse(status=HTTPStatus.CONFLICT)
            sequence += 1
            return result

        mock_skill_client = self._create_mock_skill_client(None, post_return)
        conversation_state = ConversationState(MemoryStorage())

        dialog_options = SkillDialogTests.create_skill_dialog_options(
            conversation_state, mock_skill_client, connection_name
        )
        sut = SkillDialog(dialog_options, dialog_id="dialog")
        activity_to_send = SkillDialogTests.create_send_activity()

        client = DialogTestClient(
            "test",
            sut,
            BeginSkillDialogOptions(activity=activity_to_send,),
            conversation_state=conversation_state,
        )

        client.test_adapter.add_exchangeable_token(
            connection_name, "test", "User1", "https://test", "https://test1"
        )

        final_activity = await client.send_activity(MessageFactory.text("irrelevant"))
        self.assertIsNotNone(final_activity)
        self.assertEqual(len(final_activity.attachments), 1) 
Example #9
Source File: directory.py    From loaner with Apache License 2.0 4 votes vote down vote up
def insert_user(
      self, password, family_name=_DEFAULT_ROLE_FAMILY_NAME,
      given_name=_DEFAULT_ROLE_GIVEN_NAME, primary_email=_PRIMARY_EMAIL,
      org_unit=_ORG_UNIT):
    """Creates and inserts a new Google Admin User.

    Args:
      password: str, the password to associate with the new GSuite user.
      family_name: str, the family name of the GSuite user to insert.
      given_name: str, the given name of the GSuite user to insert.
      primary_email: str, the email address of the GSuite user to insert.
      org_unit: str, the path to the Organizational Unit where the new GSuite
          user should be inserted.

    Returns:
      A dictionary object representing the new GSuite user.
          https://developers.google.com/admin-sdk/directory/v1/reference/users

    Raises:
      AlreadyExistsError: when the user with the provided email address already
          exists.
      ForbiddenError: when authorization fails.
      InsertionError: when creation fails (e.g. failed to authenticate, improper
          scopes, etc).
    """
    try:
      return self._client.users().insert(
          body={
              'name': {
                  'familyName': family_name,
                  'givenName': given_name,
              },
              'primaryEmail': primary_email,
              'password': password,
              'orgUnitPath': org_unit,
              'changePasswordAtNextLogin': False,
          },
      ).execute()
    except errors.HttpError as err:
      status = err.resp.status

      if (status == http_status.CONFLICT or
          status == http_status.INTERNAL_SERVER_ERROR):
        raise AlreadyExistsError(
            'user with email address {!r} already exists'.format(primary_email))

      if status == http_status.FORBIDDEN:
        raise ForbiddenError(_FORBIDDEN_ERROR_MSG)

      logging.error(_INSERT_USER_ERROR_MSG, primary_email, err)
      raise InsertionError(_INSERT_USER_ERROR_MSG % (primary_email, err)) 
Example #10
Source File: tag.py    From amundsenmetadatalibrary with Apache License 2.0 4 votes vote down vote up
def put(self, id: str, resource_type: ResourceType,
            tag: str, tag_type: str = 'default') -> Tuple[Any, HTTPStatus]:
        """
        Method to add a tag to existing resource.

        :param id:
        :param resource_type:
        :param tag:
        :param tag_type:
        :return:
        """

        whitelist_badges = app.config.get('WHITELIST_BADGES', [])
        if tag_type == BADGE_TYPE:
            # need to check whether the badge is part of the whitelist:
            if tag not in whitelist_badges:
                return \
                    {'message': 'The tag {} for id {} with type {} and resource_type {} '
                                'is not added successfully as badge '
                                'is not part of the whitelist'.format(tag,
                                                                      id,
                                                                      tag_type,
                                                                      resource_type.name)}, \
                    HTTPStatus.NOT_FOUND
        else:
            if tag in whitelist_badges:
                return \
                    {'message': 'The tag {} for id {} with type {} and resource_type {} '
                                'is not added successfully as tag '
                                'for it is reserved for badge'.format(tag,
                                                                      id,
                                                                      tag_type,
                                                                      resource_type.name)}, \
                    HTTPStatus.CONFLICT

        try:
            self.client.add_tag(id=id,
                                tag=tag,
                                tag_type=tag_type,
                                resource_type=resource_type)
            return {'message': 'The tag {} for id {} with type {} and resource_type {} '
                               'is added successfully'.format(tag,
                                                              id,
                                                              tag_type,
                                                              resource_type.name)}, HTTPStatus.OK
        except NotFoundException:
            return \
                {'message': 'The tag {} for table_uri {} with type {} and resource_type {} '
                            'is not added successfully'.format(tag,
                                                               id,
                                                               tag_type,
                                                               resource_type.name)}, \
                HTTPStatus.NOT_FOUND