def _get_time_arguments(self):
        """
        Get from_time and to_time from handler args and parse into valid format

        :return: (from_time, to_time)
        """
        from_time = self.get_argument('from', None)
        to_time = self.get_argument('to', None)

        # parse the value or get default value if parameter not specified
        now = arrow.utcnow()  # todo: why is the in the handler?
        try:
            if from_time is None:
                from_time = now.replace(days=-1)
            else:
                from_time = arrow.get(from_time)

            if to_time is None:
                to_time = now.replace(days=+1)
            else:
                to_time = arrow.get(to_time)
        except ParserError:
            raise HTTPError(400, "Invalid format")
        except (OverflowError, ValueError):
            raise HTTPError(400, "Date out of range")

        return from_time, to_time
    def _get_page_arguments(self):
        """
        Get page and paze_size arguments from handler and validate

        :return: (page, page_size)
        """
        try:
            page = int(self.get_argument('page', 1))
        except ValueError:
            raise HTTPError(400, "Invalid page")

        if page < 1:
            raise HTTPError(400, 'page must be >= 1')

        try:
            page_size = int(self.get_argument('page_size', 1000))
        except ValueError:
            raise HTTPError(400, "Invalid page_size")

        if page_size < 0 or page_size > options.max_page_size:
            raise HTTPError(
                400,
                'page_size must be between 0 and {}'.format(options.max_page_size))

        return page, page_size
    def post(self, repository_id, entity_id):
        """Respond with JSON containing success or error message."""
        exists = yield asset.exists(DatabaseConnection(repository_id), entity_id)

        if not exists:
            raise HTTPError(404, 'Asset "{}" does not exist '.format(entity_id))

        data = self.get_json_body(required=['ids'])
        errors = yield asset.add_ids(DatabaseConnection(repository_id), entity_id, data['ids'])

        if len(errors) > 0:
            raise HTTPError(400, errors)
        else:
            audit.log_asset_ids(entity_id, data['ids'], self.token)
            self.finish({'status': 200})
Пример #4
0
def test_request_invalid_query(fetch, url, create_namespace):
    fetch.side_effect = HTTPError(500, 'Internal Server Error')
    with pytest.raises(HTTPError) as exc:
        yield request(None, 'c8ab01', 'pay load')
    assert not create_namespace.called
    assert fetch.call_count == 1
    assert exc.value.status_code == 500
Пример #5
0
    def post(self, organisation_id):
        """Create a service.
        At this stage a basic data validation is applied. Service Model is
        responsible for more detailed validation.
        It will:
        * on success: return a service object containing id and rev
        * on validation failure: return an errors object
        * on saving to DB: raise an CouchDB exception
        """
        if not self.user.is_user(organisation_id):
            raise HTTPError(403, 'Forbidden')

        data = self.get_json_body(
            required=['name', 'location', 'service_type'])
        data['created_by'] = self.user.id
        data['organisation_id'] = organisation_id

        service = yield perch.Service.create(user=self.user, **data)

        msg = ("created service, organisation id: {}, service_id: {}, data: {}"
               .format(organisation_id, service.id, data))
        audit_log.info(self, msg)

        if service.state == State.pending:
            yield email.send_create_request_emails(self.user, service)

        self.finish({'status': 200, 'data': service.clean(user=self.user)})
    def get(self, repository_id, entity_id):
        """Respond with JSON with source_id and source_id_type for entity."""
        dbc = DatabaseConnection(repository_id)
        exists = yield asset.exists(dbc, entity_id)
        if not exists:
            raise HTTPError(404, 'Asset "{}" does not exist '.format(entity_id))

        result = yield asset.Asset.get_also_identified_by(dbc, entity_id)

        self.finish({'status': 200, 'data': result})
    def post(self, repository_id):
        """
        Retrieve offers by bulk

        :param repository_id: str
        """
        body = _unique_ids(self.get_json_body())
        try:
            result = yield Offer.retrieve_for_assets(body, DatabaseConnection(repository_id))
        except KeyError as error:
            logging.info(error.message)
            raise HTTPError(400, "Invalid object in post body")

        self.finish({'status': 200, 'data': result})
    def post(self, repository_id):
        """
        Initialise a namespace if it has not already been initialised

        :param repository_id: id of repository/namespace
        """
        # If not running in standalone mode, the RepoBaseHandler will check to ensure repository id
        # is already registered with the accounts service, and will raise a 404 if not.

        try:
            yield create_namespace(repository_id)
        except tornado.httpclient.HTTPError as exc:
            # Must be converted to a tornado.web.HTTPError for the server
            # to handle it correctly
            logging.exception(exc.message)

            if exc.code == 409:
                raise HTTPError(
                    400, 'Namespace {} already exists'.format(repository_id))
            else:
                raise HTTPError(500, 'Internal Server Error')

        self.finish({'status': 200})
    def get(self, repository_id, asset_id):
        """
        Retrieve one asset by asset_id

        :param repository_id: the id of the repository
        :param asset_id: the id of an asset
        :return: A JSON object containing an asset
        """
        db = DatabaseConnection(repository_id)
        asset_obj = yield asset.Asset.retrieve(db, asset_id)

        if not asset_obj:
            raise HTTPError(404, "asset {} not found".format(asset_id))

        self.finish({'status': 200, 'data': asset_obj})
Пример #10
0
    def post(self):
        """Create token"""
        # TODO: what if unverified user?
        data = self.get_json_body(required=['email', 'password'])
        try:
            user, token = yield User.login(data['email'], data['password'])
        except Unauthorized:
            raise HTTPError(401, 'Invalid email and/or password')

        self.finish({
            'status': 200,
            'data': {
                'token': token,
                'user': user.clean()
            }
        })
def validate_post_request(request):
    """
    Validates the request for the AssetsHandler post and returns the
    normalised data format (short content type) and body
    Throws a HTTPError if invalid
    :param handler: AssetsHandler
    """
    request = request
    errors = []

    verify_body_size(request, errors)
    data_format = check_content_type(request, errors)

    if len(errors):
        raise HTTPError(400, {'errors': errors})

    return data_format, request.body
def _validate_body(request):
    if request.body is None:
        raise HTTPError(400, "No Data in Body")
    if request.body == '':
        raise HTTPError(400, "Body is empty string")
Пример #13
0
    assert exc.value.code == 500


@patch('repository.models.framework.db.load_directory',
       return_value=make_future(None))
@patch('repository.models.framework.db._initialise_namespace',
       return_value=make_future(None))
@gen_test
def test_create_namespace(_initialise_namespace, load_directory):
    yield create_namespace('foo')
    _initialise_namespace.assert_called_once_with('foo')
    load_directory.assert_called_once_with(INITIAL_DATA, 'foo')


@patch('repository.models.framework.db.load_directory',
       side_effect=HTTPError(400, ""))
@patch('repository.models.framework.db._initialise_namespace',
       return_value=make_future(None))
@gen_test
def test_create_namespace_error_initialise_err_code(_initialise_namespace,
                                                    load_directory):
    with pytest.raises(HTTPError) as exc:
        yield create_namespace('foo')
    assert exc.value.status_code == 400


@patch('repository.models.framework.db.options')
@gen_test
def test_url_contains_url_repo_db(options):
    options.url_repo_db = 'https://localhost'
    result = _namespace_url('namespace01')