Python httplib.CONFLICT Examples

The following are 7 code examples of httplib.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 httplib , 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: votes_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testPost_User_Duplicate(self):
    params = {'wasYesVote': 'true'}

    with self.LoggedInUser(email_addr=self.user_2.email):
      self.testapp.post(
          self.ROUTE % self.santa_blockable.key.id(), params)

      self.testapp.post(
          self.ROUTE % self.santa_blockable.key.id(), params,
          status=httplib.CONFLICT) 
Example #3
Source File: votes_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testPost_DuplicateVoteError(self, mock_vote):
    with self.LoggedInUser():
      self.testapp.post(
          self.ROUTE % test_utils.RandomSHA256(),
          params={'wasYesVote': 'true'},
          status=httplib.CONFLICT) 
Example #4
Source File: votes.py    From upvote with Apache License 2.0 5 votes vote down vote up
def post(self, blockable_id):
    """Handle votes from users."""

    was_yes_vote = (self.request.get('wasYesVote') == 'true')
    role = self.request.get('asRole', default_value=self.user.highest_role)
    vote_weight = self._GetVoteWeight(role)

    logging.info(
        'User %s is using the %s role to cast a %s%s vote for %s',
        self.user.nickname, role, '+' if was_yes_vote else '-', vote_weight,
        blockable_id)

    try:
      vote = voting_api.Vote(self.user, blockable_id, was_yes_vote, vote_weight)
    except voting_api.BlockableNotFoundError:
      self.abort(httplib.NOT_FOUND, explanation='Application not found')
    except voting_api.UnsupportedClientError:
      self.abort(httplib.BAD_REQUEST, explanation='Unsupported client')
    except voting_api.InvalidVoteWeightError:
      self.abort(httplib.BAD_REQUEST, explanation='Invalid voting weight')
    except voting_api.DuplicateVoteError:
      self.abort(httplib.CONFLICT, explanation='Vote already exists')
    except voting_api.OperationNotAllowedError as e:
      self.abort(httplib.FORBIDDEN, explanation=e.message)
    except Exception as e:  # pylint: disable=broad-except
      self.abort(httplib.INTERNAL_SERVER_ERROR, explanation=e.message)
    else:

      # Update the user's last vote date
      self.user.last_vote_dt = datetime.datetime.utcnow()
      self.user.put()

      # Augment the response dict with related voting data.
      blockable = binary_models.Blockable.get_by_id(blockable_id)
      blockable_dict = blockable.to_dict()
      allowed, reason = voting_api.IsVotingAllowed(blockable.key)
      blockable_dict['is_voting_allowed'] = allowed
      blockable_dict['voting_prohibited_reason'] = reason

      self.respond_json({'blockable': blockable_dict, 'vote': vote}) 
Example #5
Source File: blockables_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testPost_Admin_InsertExistingBlockable(self):
    """Admin tries to inject an existing blockable."""
    santa_blockable = test_utils.CreateSantaBlockable()
    sha256 = santa_blockable.key.id()
    params = {'type': constants.BLOCKABLE_TYPE.SANTA_BINARY, 'hash': sha256}

    with self.LoggedInUser(admin=True):
      self.testapp.post(self.ROUTE % sha256, params, status=httplib.CONFLICT)

    self.assertNoBigQueryInsertions() 
Example #6
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 #7
Source File: blockables.py    From upvote with Apache License 2.0 4 votes vote down vote up
def _insert_blockable(self, blockable_id, timestamp):

    blockable_type = self.request.get('type')

    model_class_map = {
        constants.BLOCKABLE_TYPE.SANTA_BINARY:
            binary_models.SantaBlockable,
        constants.BLOCKABLE_TYPE.SANTA_CERTIFICATE:
            cert_models.SantaCertificate}
    model_class = model_class_map.get(blockable_type, None)

    if not model_class:
      self.abort(
          httplib.BAD_REQUEST,
          explanation='No Model class found for "%s"' % blockable_type)

    elif model_class.get_by_id(blockable_id):
      self.abort(
          httplib.CONFLICT,
          explanation='Blockable "%s" already exists' % blockable_id)

    else:
      flag = (self.request.get('flagged') == 'true')

      logging.info('Creating new %s %s', model_class.__name__, blockable_id)
      blockable = model_class.get_or_insert(
          blockable_id,
          file_name=self.request.get('fileName'),
          publisher=self.request.get('publisher'),
          flagged=flag,
          id_type=constants.ID_TYPE.SHA256)
      blockable.InsertBigQueryRow(
          constants.BLOCK_ACTION.FIRST_SEEN, timestamp=timestamp)

      # If one was provided, create a note to accompany the blockable.
      note_text = self.request.get('notes')
      if note_text:
        note_key = note_models.Note.GenerateKey(note_text, blockable.key)
        note = note_models.Note(
            key=note_key, message=note_text, author=self.user.key.id())
        note.put()

        blockable.notes.append(note.key)

      blockable.put()
      self.respond_json(blockable)