Python httplib.BAD_REQUEST Examples

The following are 30 code examples of httplib.BAD_REQUEST(). 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: playground.py    From cloud-playground with Apache License 2.0 6 votes vote down vote up
def post(self):  # pylint:disable-msg=invalid-name
    """Handles HTTP POST requests."""
    if not users.is_current_user_admin():
      self.response.set_status(httplib.UNAUTHORIZED)
      return
    project_id = self.request.data['project_id']
    if not project_id:
      Abort(httplib.BAD_REQUEST, 'project_id required')
    project = model.GetProject(project_id)
    if not project:
      Abort(httplib.NOT_FOUND,
            'failed to retrieve project {}'.format(project_id))
    repo_url = project.template_url
    repo = model.GetRepo(repo_url)
    model.CreateRepoAsync(owner=model.GetOrCreateUser(repo.owner),
                          repo_url=repo.key.id(),
                          html_url=repo.html_url,
                          name=repo.name,
                          description=repo.description,
                          show_files=repo.show_files,
                          read_only_files=repo.read_only_files,
                          read_only_demo_url=repo.read_only_demo_url) 
Example #2
Source File: validation_error_handler.py    From flasgger with MIT License 6 votes vote down vote up
def validation_error_try_to_accept(err, data, schema):
    """
    Custom validation error handler which attempts alternative
    validation
    """
    if not isinstance(err, ValidationError):
        abort(Response(err, status=HTTPStatus.BAD_REQUEST))

    alernative_schema = dict(schema)
    alernative_schema['properties']['running_time'].update({
        'description': "Films's running time",
        'type': 'integer',
        'example': 169
    })

    try:
        jsonschema.validate(data, alernative_schema)
    except ValidationError as err:
        abort(Response(str(err), status=400)) 
Example #3
Source File: settings.py    From upvote with Apache License 2.0 6 votes vote down vote up
def post(self, key_name):  # pylint: disable=g-bad-name
    """Post handler for a single API key."""

    value = self.request.get('value', None)
    if value is None:
      self.abort(httplib.BAD_REQUEST, explanation='No value provided')

    if key_name == 'virustotal':
      singleton.VirusTotalApiAuth.SetInstance(api_key=value)
    elif key_name == 'bit9':
      singleton.Bit9ApiAuth.SetInstance(api_key=value)
    else:
      self.abort(httplib.BAD_REQUEST, explanation='Invalid key name')


# The Webapp2 routes defined for these handlers. 
Example #4
Source File: votes.py    From upvote with Apache License 2.0 6 votes vote down vote up
def _GetVoteWeight(self, role):
    if not role:
      return self.user.vote_weight

    role_weights = settings.VOTING_WEIGHTS
    vote_weight = role_weights.get(role)
    if vote_weight is None:
      self.abort(
          httplib.BAD_REQUEST,
          explanation='Invalid role provided: %s' % role)

    valid_access = role in self.user.roles or self.user.is_admin
    if not valid_access:
      self.abort(
          httplib.FORBIDDEN,
          explanation='User "%s" does not have role: %s' % (
              self.user.nickname, role))

    return vote_weight 
Example #5
Source File: exemptions_test.py    From upvote with Apache License 2.0 6 votes vote down vote up
def testPost_BadRequest_InvalidRenewalError(self):

    user = test_utils.CreateUser()
    host = test_utils.CreateSantaHost(primary_user=user.nickname)

    params = {
        'duration': 'DAY',
        'reason': constants.EXEMPTION_REASON.DEVELOPER_MACOS}

    with self.LoggedInUser(user=user):
      self.testapp.post(
          self.ROUTE % host.key.id(), params=params, status=httplib.OK)
      self.testapp.post(
          self.ROUTE % host.key.id(), params=params, status=httplib.BAD_REQUEST)

    exm = exemption_models.Exemption.Get(host.key.id())
    self.assertEqual(constants.EXEMPTION_STATE.REQUESTED, exm.state)
    self.assertBigQueryInsertion(constants.BIGQUERY_TABLE.EXEMPTION)
    self.mock_process.assert_called_once() 
Example #6
Source File: blockables.py    From upvote with Apache License 2.0 6 votes vote down vote up
def get(self, platform, blockable_type):
    normalized_platform = platform.lower()
    normalized_blockable_type = blockable_type.lower()

    # Set the target Model to query against based on the URL arguments.
    platform_map = _MODEL_MAP.get(normalized_platform)
    if not platform_map:
      self.abort(
          httplib.BAD_REQUEST, 'Unknown platform: %s' % normalized_platform)
    elif normalized_blockable_type not in platform_map:
      self.abort(
          httplib.BAD_REQUEST,
          'Unknown Blockable type: %s' % normalized_blockable_type)

    blockable_class = platform_map.get(normalized_blockable_type)
    if not blockable_class:
      self.abort(
          httplib.BAD_REQUEST,
          'Unsupported platform-type pair: %s, %s' % (
              normalized_platform, normalized_blockable_type))

    BlockableQueryHandler.MODEL_CLASS = blockable_class

    # With target Model class set, trigger the query execution.
    self._Query() 
Example #7
Source File: blockables.py    From upvote with Apache License 2.0 6 votes vote down vote up
def get(self, package_id):
    blockable = binary_models.Blockable.get_by_id(package_id)
    if not blockable:
      self.abort(httplib.NOT_FOUND, explanation='Package not found.')
    elif not isinstance(blockable, package_models.Package):
      self.abort(
          httplib.BAD_REQUEST,
          explanation='Blockable is not a Package: %s' % blockable)
    elif not isinstance(blockable, package_models.SantaBundle):
      self.abort(
          httplib.BAD_REQUEST,
          explanation='Only SantaBundles currently supported')

    # Order by the rel_path first, and then by the file_name which should
    # effectively sort by the full relative path in the bundle.
    query = package_models.SantaBundleBinary.query(
        ancestor=blockable.key).order(
            package_models.SantaBundleBinary.rel_path,
            package_models.SantaBundleBinary.file_name)

    binaries = query.fetch()
    self.respond_json(binaries) 
Example #8
Source File: blockables.py    From upvote with Apache License 2.0 6 votes vote down vote up
def post(self, blockable_id):
    blockable_id = blockable_id.lower()
    blockable = binary_models.Blockable.get_by_id(blockable_id)
    if not blockable:
      self.abort(httplib.NOT_FOUND, explanation='Blockable not found.')
    elif blockable.GetPlatformName() != constants.PLATFORM.WINDOWS:
      self.abort(httplib.BAD_REQUEST, explanation='Must be a Bit9 blockable')
    elif not isinstance(blockable, binary_models.Binary):
      self.abort(httplib.BAD_REQUEST, explanation='Must be a Binary')

    force_installer = self.request.get('value', None)
    if force_installer is None:
      self.abort(httplib.BAD_REQUEST, explanation='No installer state provided')

    new_policy = (
        constants.RULE_POLICY.FORCE_INSTALLER
        if force_installer.lower() == 'true'
        else constants.RULE_POLICY.FORCE_NOT_INSTALLER)

    new_installer_state = self._SetInstallerPolicy(blockable_id, new_policy)
    self.respond_json(new_installer_state)


# The Webapp2 routes defined for these handlers. 
Example #9
Source File: rules.py    From upvote with Apache License 2.0 6 votes vote down vote up
def get(self, rule_key):
    logging.info('Rule handler get method called with key: %s', rule_key)
    key = datastore_utils.GetKeyFromUrlsafe(rule_key)
    if not key:
      self.abort(
          httplib.BAD_REQUEST,
          explanation='Rule key %s could not be parsed' % rule_key)

    rule = key.get()
    if rule:
      response = rule.to_dict()
      response['target_id'] = rule.key.parent().id()
      self.respond_json(response)
    else:
      self.abort(httplib.NOT_FOUND, explanation='Rule not found')


# The Webapp2 routes defined for these handlers. 
Example #10
Source File: cloudstorage_stub.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def put_empty(self, token):
    """Empty put is used to query upload progress.

    The file must has not finished upload.

    Args:
      token: upload token returned by post_start_creation.

    Returns:
      last offset uploaded. -1 if none has been uploaded.

    Raises:
      ValueError: if token matches no in progress uploads.
    """
    ns = namespace_manager.get_namespace()
    try:
      namespace_manager.set_namespace('')
      gcs_file = _AE_GCSFileInfo_.get_by_key_name(token)
      if not gcs_file:
        raise ValueError('Invalid token', httplib.BAD_REQUEST)
      return gcs_file.next_offset - 1
    finally:
      namespace_manager.set_namespace(ns) 
Example #11
Source File: api.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
def make_query():
    try:
        query = parser.generate_query(request.json['query'])
        event_type, action = DataModelQueryLayer.get_data_model(query)
        return {'object': event_type.object_name, 'action': action, 'query': query}, httplib.OK

    except InvalidFieldError:
        return {'error': 'Invalid Data Model field in query'}, httplib.BAD_REQUEST

    except InvalidActionError:
        return {'error': 'Invalid Data Model action in query'}, httplib.BAD_REQUEST

    except InvalidObjectError:
        return {'error': 'Invalid Data Model object in query'}, httplib.BAD_REQUEST

    except parser.ParserError:
        return {'error': 'Unable to parse query'}, httplib.BAD_REQUEST 
Example #12
Source File: api.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
def submit_analytic(user=None):
    if 'update_many' in request.args:
        if isinstance(request.json, dict) and request.json.get('analytics') is not None:
            count = 0
            for content in request.json['analytics']:
                _id = content.pop('_id', None)
                analytic = Analytic.objects.with_id(_id)
                if analytic is not None:
                    count += analytic.update(**content)

            return Analytic.objects(), httplib.OK
        return {}, httplib.BAD_REQUEST

    # creating a new analytic
    else:
        if request.json.get('platform', 'CASCADE') == 'CASCADE':
            analytic = CascadeAnalytic._from_son(request.json)
        else:
            analytic = ExternalAnalytic._from_son(request.json)
        analytic.save()

    return analytic.id, httplib.OK 
Example #13
Source File: api.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
def automate_session_custom(session, user=None):
    """
    :type session: cascade.session.Session
    :type user: User
    """
    session = Session.objects.with_id(session)
    if not session:
        return None, httplib.NOT_FOUND

    if not isinstance(request.json, dict):
        return None, httplib.BAD_REQUEST

    query = DataModelQuery._from_son(request.json['query'])
    job = CustomQueryJob.update_existing(session=session, event_query=query, user=user)
    job.submit()
    return None, httplib.OK 
Example #14
Source File: playground.py    From cloud-playground with Apache License 2.0 6 votes vote down vote up
def post(self):  # pylint:disable-msg=invalid-name
    """Handles HTTP POST requests."""
    repo_url = self.request.data.get('repo_url')
    if not repo_url:
      Abort(httplib.BAD_REQUEST, 'repo_url required')
    repo = model.GetRepo(repo_url)
    if not repo:
      html_url = name = description = repo_url
      repo = model.CreateRepoAsync(owner=model.GetManualTemplateOwner(),
                                   repo_url=repo_url,
                                   html_url=html_url,
                                   name=name,
                                   description=description,
                                   show_files=[],
                                   read_only_files=[],
                                   read_only_demo_url=None)
    project = repo.project.get()
    if not project or project.in_progress_task_name:
      Abort(httplib.REQUEST_TIMEOUT,
            'Sorry. Requested template is not yet available. '
            'Please try again in 30 seconds.')
    return self.DictOfProject(project) 
Example #15
Source File: playground.py    From cloud-playground with Apache License 2.0 6 votes vote down vote up
def post(self):  # pylint:disable-msg=invalid-name
    """Handles HTTP POST requests."""
    repo_url = self.request.data.get('repo_url')
    if not repo_url:
      Abort(httplib.BAD_REQUEST, 'repo_url required')
    repo = model.GetRepo(repo_url)
    if not repo:
      html_url = name = description = repo_url
      repo = model.CreateRepoAsync(owner=model.GetManualTemplateOwner(),
                                   repo_url=repo_url,
                                   html_url=html_url,
                                   name=name,
                                   description=description,
                                   show_files=[],
                                   read_only_files=[],
                                   read_only_demo_url=None)
    template_project = repo.project.get()
    if not template_project or template_project.in_progress_task_name:
      Abort(httplib.REQUEST_TIMEOUT,
            'Sorry. Requested template is not yet available. '
            'Please try again in 30 seconds.')
    expiration_seconds = self.request.data.get('expiration_seconds')
    project = model.CopyProject(self.user, template_project, expiration_seconds,
                                new_project_name=template_project.project_name)
    return self.DictOfProject(project) 
Example #16
Source File: api.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
def create_user():
    if not settings.load()['config'].get('allow_account_creation', False):
        return JSONResponse(status=httplib.FORBIDDEN)

    """ This API route is used by the create new account template to add a new user into Mongo """
    if isinstance(request.json, dict):
        args = request.json
        if args.get('username') and args.get('password'):
            try:
                user = users.create_user(args['username'], args['password'], args.get('email'), args.get('full_name'))
            except users.PasswordPolicyError as error:
                regex, rules = error.args
                return JSONResponse({'violation': {'regex': regex, 'rules': rules}}, httplib.BAD_REQUEST)

            if user is not None:
                response = Response(status=httplib.CREATED)
                response.set_cookie('user-token', user.generate_token(), max_age=datetime.timedelta(days=7))
                return response
            else:
                return JSONResponse({'message': 'Username already exists!'}, status=httplib.BAD_REQUEST)

    return JSONResponse({'message': 'Username, email and password are required'}, status=httplib.BAD_REQUEST) 
Example #17
Source File: events_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testUserGetBadKey(self):
    """Getting an event of the requesting user's by key."""
    with self.LoggedInUser(user=self.user_1):
      self.testapp.get(self.ROUTE % 'NotARealKey', status=httplib.BAD_REQUEST) 
Example #18
Source File: settings_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testBadValue(self):
    with self.LoggedInUser(admin=True):
      self.testapp.post(
          self.ROUTE % 'virustotal', {}, status=httplib.BAD_REQUEST) 
Example #19
Source File: events_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testAdminGetQueryNoSearch(self):
    """Admin searching with no search term."""
    params = {'searchBase': 'hostId',
              'asAdmin': True}

    with self.LoggedInUser(admin=True):
      self.testapp.get(self.ROUTE, params, status=httplib.BAD_REQUEST) 
Example #20
Source File: events_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testAdminGetQueryNoSearchBase(self):
    """Admin searching with no searchBase param."""
    params = {'search': 'AAAAAAAA-1111-BBBB-2222-CCCCCCCCCCCC',
              'asAdmin': True}

    with self.LoggedInUser(admin=True):
      self.testapp.get(self.ROUTE, params, status=httplib.BAD_REQUEST) 
Example #21
Source File: events_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testAdminGetQueryBadPlatform(self):
    """Admin searching with a platform param mismatch with the searchBase."""
    params = {'search': 'DoesntMatter',
              'searchBase': 'bundleId',
              'asAdmin': True}

    with self.LoggedInUser(admin=True):
      self.testapp.get(self.ROUTE + '/bit9', params, status=httplib.BAD_REQUEST) 
Example #22
Source File: votes.py    From upvote with Apache License 2.0 5 votes vote down vote up
def get(self, vote_key):
    logging.info('Vote handler get method called with key: %s', vote_key)
    key = datastore_utils.GetKeyFromUrlsafe(vote_key)
    if not key:
      self.abort(
          httplib.BAD_REQUEST,
          explanation='Vote key %s could not be parsed' % vote_key)

    vote = key.get()
    if vote:
      response = vote.to_dict()
      response['candidate_id'] = vote.key.parent().parent().id()
      self.respond_json(response)
    else:
      self.abort(httplib.NOT_FOUND, explanation='Vote not found.') 
Example #23
Source File: votes_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testAdminGetBadKey(self):
    """Admin gets a vote by an invalid key."""
    with self.LoggedInUser(admin=True):
      self.testapp.get(self.ROUTE % 'BadKey', status=httplib.BAD_REQUEST) 
Example #24
Source File: exemptions_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testPost_BadRequest_JustificationMissing(self):

    with self.LoggedInUser(admin=True):
      self.testapp.post(self.ROUTE % self.host_id, status=httplib.BAD_REQUEST)

    self.assertEqual(
        constants.EXEMPTION_STATE.ESCALATED, self.exm_key.get().state) 
Example #25
Source File: exemptions_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testPost_BadRequest_JustificationMissing(self):

    with self.LoggedInUser(admin=True):
      self.testapp.post(self.ROUTE % self.host_id, status=httplib.BAD_REQUEST)

    self.assertEqual(
        constants.EXEMPTION_STATE.ESCALATED, self.exm_key.get().state) 
Example #26
Source File: exemptions_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testPost_BadRequest_InvalidDurationErrorProvided(self):

    user = test_utils.CreateUser()
    host = test_utils.CreateSantaHost(primary_user=user.nickname)

    params = {
        'duration': 'some_invalid_duration',
        'reason': constants.EXEMPTION_REASON.DEVELOPER_MACOS}

    with self.LoggedInUser(user=user):
      self.testapp.post(
          self.ROUTE % host.key.id(), params=params, status=httplib.BAD_REQUEST)
    self.mock_process.assert_not_called() 
Example #27
Source File: exemptions_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testPost_BadRequest_NoDurationProvided(self):

    user = test_utils.CreateUser()
    host = test_utils.CreateSantaHost(primary_user=user.nickname)

    params = {
        'reason': constants.EXEMPTION_REASON.DEVELOPER_MACOS}

    with self.LoggedInUser(user=user):
      self.testapp.post(
          self.ROUTE % host.key.id(), params=params, status=httplib.BAD_REQUEST)
    self.mock_process.assert_not_called() 
Example #28
Source File: exemptions_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testPost_BadRequest_InvalidReasonErrorProvided(self):

    user = test_utils.CreateUser()
    host = test_utils.CreateSantaHost(primary_user=user.nickname)

    params = {
        'term': 'DAY',
        'reason': 'some_invalid_reason'}

    with self.LoggedInUser(user=user):
      self.testapp.post(
          self.ROUTE % host.key.id(), params=params, status=httplib.BAD_REQUEST)
    self.mock_process.assert_not_called() 
Example #29
Source File: exemptions_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testPost_BadRequest_NoReasonProvided(self):

    user = test_utils.CreateUser()
    host = test_utils.CreateSantaHost(primary_user=user.nickname)

    params = {'term': 'DAY'}

    with self.LoggedInUser(user=user):
      self.testapp.post(
          self.ROUTE % host.key.id(), params=params, status=httplib.BAD_REQUEST)
    self.mock_process.assert_not_called() 
Example #30
Source File: settings_test.py    From upvote with Apache License 2.0 5 votes vote down vote up
def testBadKeyName(self):
    with self.LoggedInUser(admin=True):
      self.testapp.post(
          self.ROUTE % 'not-a-key', {'value': 'good-value'},
          status=httplib.BAD_REQUEST)