How to use the girder.api.rest.RestException function in girder

To help you get started, we’ve selected a few girder examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Kitware / minerva / plugins / geoJSON / server / __init__.py View on Github external
limit, offset, sort = self.getPagingParameters(params, 'name')
        latitude = params.get('latitude', 'meta.latitude')
        longitude = params.get('longitude', 'meta.longitude')

        spec = {
            'type': 'point',
            'latitude': latitude,
            'longitude': longitude,
            'keys': ['meta', 'name', 'description', '_id'],
            'flatten': ['meta']
        }

        try:
            query = bson.json_util.loads(params['q'])
        except ValueError:  # pragma: no cover
            raise RestException('The query parameter must be a JSON object.')

        events.trigger('geojson.points', info={
            'spec': spec,
            'query': query
        })

        # make sure the lat/lon are whitelisted keys to prevent private
        # data leaking
        if spec['latitude'].split('.')[0] not in spec['keys'] or \
                spec['longitude'].split('.')[0] not in spec['keys']:
            raise RestException('Invalid latitude/longitude key.', code=402)

        coll = features.FeatureCollection(points=spec)

        item = ModelImporter().model('item')
        cursor = item.find(
github Kitware / cumulus / girder / newt / newt / rest.py View on Github external
}

        user = User().findOne(query)
        set_id = not user

        # Existing users using NEWT for the first time will not have an user id
        if not user:
            user = User().findOne({'email': email})

        # Create the user if it's still not found
        if not user:
            policy = Setting().get(SettingKey.REGISTRATION_POLICY)
            if policy == 'closed':
                ignore = Setting().get(PluginSettings.IGNORE_REGISTRATION_POLICY)
                if not ignore:
                    raise RestException(
                        'Registration on this instance is closed. Contact an '
                        'administrator to create an account for you.')

            user = User().createUser(
                login=user_name, password=None, firstName=first_name,
                lastName=last_name, email=email)
        else:
            # Update user data from NEWT
            if email != user['email']:
                user['email'] = email
                dirty = True
            # Don't set names to empty string
            if first_name != user['firstName'] and first_name:
                user['firstName'] = first_name
                dirty = True
            if last_name != user['lastName'] and last_name:
github Kitware / HPCCloud / server / hpccloud / hpccloud_plugin / simulations.py View on Github external
def set_active(self, simulation, stepName, params):

        if stepName not in simulation.get('steps', {}):
            raise RestException('Invalid step name', 400)

        simulation['active'] = stepName

        return self._model.save(simulation)
github Kitware / cumulus / girder / taskflow / taskflow / taskflows.py View on Github external
def update(self, taskflow, params):
        user = self.getCurrentUser()
        immutable = ['access', '_id', 'taskFlowClass', 'log', 'activeTaskCount']
        updates = getBodyJson()
        if not updates:
            raise RestException('A body must be provided', code=400)

        for p in updates:
            if p in immutable:
                raise RestException('\'%s\' is an immutable property' % p, 400)

        taskflow = self._model.update_taskflow(user, taskflow, updates)

        return taskflow
github Kitware / minerva / girder / api / rest.py View on Github external
else:
                self._defaultAccess(handler)
                val = handler(**kwargs)

            # Fire the after-call event that has a chance to augment the
            # return value of the API method that was called. You can
            # reassign the return value completely by adding a response to
            # the event and calling preventDefault() on it.
            kwargs['returnVal'] = val
            event = events.trigger('.'.join((eventPrefix, 'after')), kwargs)
            if event.defaultPrevented and len(event.responses) > 0:
                val = event.responses[0]

            return val

        raise RestException('No matching route for "%s %s"' % (
            method.upper(), '/'.join(path)))
github Kitware / candela / app / resonantlab / server / datasetItem.py View on Github external
def setupDataset(self, item, params, user):
        metadata = item.get('meta', {})
        rlab = metadata.get('rlab', {})
        rlab['itemType'] = 'dataset'
        rlab['versionNumber'] = self.app.versioning.versionNumber({})

        # Determine fileId
        if 'fileId' in params:
            # We were given the fileId
            rlab['fileId'] = params['fileId']
        else:
            # Use the first file in this item
            childFiles = [f for f in self.model('item').childFiles(item=item)]
            if (len(childFiles) == 0):
                raise RestException('Item contains no files')
            rlab['fileId'] = childFiles[0]['_id']

        # Determine format
        fileObj = None
        if 'fileId' in rlab:
            fileObj = self.model('file').load(rlab['fileId'], user=user)
            if getDbInfoForFile(fileObj) is not None:
                # All database info is returned internally as CSV.
                # TODO: this will change soon!
                rlab['format'] = 'csv'
                params['dialect'] = '{}'    # use default parsing settings
            else:
                exts = fileObj.get('exts', [])
                mimeType = fileObj.get('mimeType', '').lower()
                if 'json' in exts or 'json' in mimeType:
                    rlab['format'] = 'json'
github Kitware / minerva / girder / api / v1 / resource.py View on Github external
:param params: a dictionary of parameters that must include 'resources'
        :param allowedModels: if present, an iterable of models that may be
                              included in the resources.
        :returns: the JSON decoded resource dictionary.
        """
        self.requireParams(('resources', ), params)
        try:
            resources = json.loads(params['resources'])
        except ValueError:
            raise RestException('The resources parameter must be JSON.')
        if not isinstance(resources, dict):
            raise RestException('Invalid resources format.')
        if allowedModels:
            for key in resources:
                if key not in allowedModels:
                    raise RestException('Resource type not supported.')
        count = sum([len(resources[key]) for key in resources])
        if not count:
            raise RestException('No resources specified.')
        return resources
github Kitware / cumulus / girder / cumulus / server / ssh.py View on Github external
def get_sshkey(cluster, params):
    if 'sshkey' not in cluster:
        raise RestException('No such resource', 400)

    return {
        'publickey': cluster['sshkey']
    }
github Kitware / cumulus / girder / cumulus / cumulus_plugin / job.py View on Github external
del body['onTerminate']['scriptId']
            body['onTerminate']['commands'] = script['commands']

        if 'input' in body:
            if not isinstance(body['input'], list):
                raise RestException('input must be a list', 400)

            for i in body['input']:
                if i['path'] == body['name']:
                    raise RestException('input can\'t be the same as job name',
                                        400)

        if 'output' in body:
            if not isinstance(body['output'], list):
                raise RestException('output must be a list', 400)

        job = self._model.create(user, body)

        cherrypy.response.status = 201
        cherrypy.response.headers['Location'] = '/jobs/%s' % job['_id']

        return self._clean(job)
github Kitware / HPCCloud / server / pvwproxy / pvwproxy_plugin / proxy.py View on Github external
def add_entry(self, params):
        body = getBodyJson()

        if 'key' not in body:
            raise RestException('key is required', code=400)
        if 'host' not in body:
            raise RestException('host is required', code=400)
        if 'port' not in body:
            raise RestException('port is required', code=400)

        key = body['key']
        host = body['host']
        port = body['port']

        with LockFile(self._proxy_file_path):
            db = None
            try:
                db = dbm.open(self._proxy_file_path, 'c')
                # Encode the slash
                db[key] = '%s:%s' % (host, port)
            finally:
                if db:
                    db.close()