Python falcon 模块,HTTP_400 实例源码

我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用falcon.HTTP_400

项目:gyr    作者:non-Jedi    | 项目源码 | 文件源码
def on_put(self, request, response, txn_id=None):
        """Responds to PUT request containing events."""
        response.body = "{}"

        # Check whether repeat txn_id
        if not self._is_new(txn_id):
            response.status = falcon.HTTP_200
            return

        request.context["body"] = request.stream.read()
        try:
            events = json.loads(request.context["body"].decode("utf-8"))["events"]
        except(KeyError, ValueError, UnicodeDecodeError):
            response.status = falcon.HTTP_400
            response.body = "Malformed request body"
            return

        if self.handler(EventStream(events, self.Api)):
            response.status = falcon.HTTP_200
        else:
            response.status = falcon.HTTP_400
项目:ScheduleStorm_Server    作者:Step7750    | 项目源码 | 文件源码
def on_get(self, req, resp, uni, term):
        # The term must be a string since the threads represent them as such
        if uni in uniThreads and term in uniThreads[uni].getTerms():
            if uniThreads[uni].isScraping:
                # we don't want to return data while scraping, send error (configure nginx to send stale data if it can)
                resp.status = falcon.HTTP_500
                resp.body = json.dumps(
                    {"error": "We're currently scraping this university, please check back in a couple minutes!"}
                ).encode('utf-8')
            else:
                # Get course/subject list
                subject_list = json.dumps(uniThreads[uni].getSubjectListAll(term), sort_keys=True).encode('utf-8')

                # set the etag and body
                resp.etag = "W/" + hashlib.sha1(subject_list).hexdigest()
                resp.body = subject_list
        else:
            # Couldn't find the uni or term, send error
            resp.status = falcon.HTTP_400
            resp.body = json.dumps(
                {"error": "The specified university or term was not found"}
            ).encode('utf-8')
项目:MusicBot    作者:BjoernPetersen    | 项目源码 | 文件源码
def login(username, password, response=None):
    """
    Logs user in. Returns status 400 response if user doesn't exist or password is wrong.
    :param username: a username
    :param password: a password
    :return: a token to authenticate with
    """
    if not username or not username.strip():
        logger.debug("Tried to log in with empty username")
        response.status = falcon.HTTP_400
        return "empty username"
    username = username.strip().lower()
    client = _get_client(username)
    if not client:
        logger.debug("Tried to log in with unknown username: %s", username)
        response.status = falcon.HTTP_400
        return "unknown"
    success = bcrypt_sha256.verify(password, client.pw_hash)
    if not success:
        logger.debug("Tried to log in with wrong password as user %s", username)
        response.status = falcon.HTTP_400
        return "wrong password"
    logger.debug("New user login: %s", username)
    return _create_user_token(username, client.permissions)
项目:MusicBot    作者:BjoernPetersen    | 项目源码 | 文件源码
def suggestions(api_name, max_fetch: hug.types.number = 10, response=None):
    max_fetch = min(10, max(1, max_fetch))

    try:
        api = music_api_names[api_name]
    except KeyError:
        logger.debug("Requested suggestions for unknown API %s", api_name)
        response.status = falcon.HTTP_400
        return "Unknown API"

    if isinstance(api, AbstractSongProvider):
        return list(map(Song.to_json, api.get_suggestions(max_fetch)))
    else:
        logger.debug("Tried to get suggestions for API %s which isn't a SongProvider", api_name)
        response.status = falcon.HTTP_400
        return []
项目:MusicBot    作者:BjoernPetersen    | 项目源码 | 文件源码
def get_active_playlist(user: hug.directives.user, response=None):
    """
    Get the active playlist of the offline API.
    :return: the active playlist of the form {'playlist_id': <id>, 'playlist_name': <name>}
    """
    if not has_permission(user, ["admin", "mod", "select_playlist"]):
        response.status = falcon.HTTP_FORBIDDEN
        return "Forbidden"

    try:
        api = music_api_names['offline_api']
        playlist_tuple = api.get_active_playlist()
        if not playlist_tuple:
            return None
        return {'playlist_id': playlist_tuple[0], 'playlist_name': playlist_tuple[1]}
    except KeyError:
        response.status = falcon.HTTP_400
        return "Not in offline mode"
项目:MusicBot    作者:BjoernPetersen    | 项目源码 | 文件源码
def mark_active(playlist_id: str, user: hug.directives.user, response=None):
    """
    Mark a playlist as active in offline mode.
    Needs admin, mod or select_playlist permission.
    :param playlist_id: the playlist ID as returned by get_available_playlists
    """
    if not has_permission(user, ["admin", "mod", "select_playlist"]):
        response.status = falcon.HTTP_FORBIDDEN
        return "Forbidden"

    try:
        try:
            api = music_api_names['offline_api']
        except KeyError:
            response.status = falcon.HTTP_400
            return "Not in offline mode"
        api.set_active_playlist(playlist_id)
        return "OK"
    except ValueError:
        response.status = falcon.HTTP_UNPROCESSABLE_ENTITY
        return "Unknown ID"
项目:armada    作者:att-comdev    | 项目源码 | 文件源码
def on_post(self, req, resp):
        try:
            manifest = self.req_yaml(req)
            documents = list(manifest)

            message = {
                'valid': validate_armada_documents(documents)
            }

            resp.status = falcon.HTTP_200
            resp.body = json.dumps(message)
            resp.content_type = 'application/json'

        except Exception:
            err_message = 'Failed to validate Armada Manifest'
            self.error(req.context, err_message)
            self.return_error(
                resp, falcon.HTTP_400, message=err_message)
项目:drydock    作者:att-comdev    | 项目源码 | 文件源码
def task_validate_design(self, req, resp, json_data):
        """Create async task for validate design."""
        action = json_data.get('action', None)

        if action != 'validate_design':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_validate_design"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False)
项目:drydock    作者:att-comdev    | 项目源码 | 文件源码
def task_prepare_site(self, req, resp, json_data):
        """Create async task for prepare site."""
        action = json_data.get('action', None)

        if action != 'prepare_site':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_prepare_site"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False)
项目:drydock    作者:att-comdev    | 项目源码 | 文件源码
def task_verify_nodes(self, req, resp, json_data):
        """Create async task for verify node."""
        action = json_data.get('action', None)

        if action != 'verify_nodes':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_verify_nodes"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False)
项目:drydock    作者:att-comdev    | 项目源码 | 文件源码
def task_prepare_nodes(self, req, resp, json_data):
        """Create async task for prepare node."""
        action = json_data.get('action', None)

        if action != 'prepare_nodes':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_prepare_nodes"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False)
项目:drydock    作者:att-comdev    | 项目源码 | 文件源码
def task_deploy_nodes(self, req, resp, json_data):
        """Create async task for deploy node."""
        action = json_data.get('action', None)

        if action != 'deploy_nodes':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_deploy_nodes"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False)
项目:drydock    作者:att-comdev    | 项目源码 | 文件源码
def task_destroy_nodes(self, req, resp, json_data):
        """Create async task for destroy node."""
        action = json_data.get('action', None)

        if action != 'destroy_nodes':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_destroy_nodes"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False)
项目:Cuppa    作者:flipkart-incubator    | 项目源码 | 文件源码
def on_post(self, req, resp):
        payload = json.loads(req.stream.read())
        pi = PredictionInput()
        if ('url' in payload.keys()) and ('modelId' in payload.keys()):
            pi.url = payload['url']
            pi.model_id = payload['modelId']
        else:
            resp.status = falcon.HTTP_400
            raise falcon.HTTPBadRequest("Bad Request", "Url and(or) modelId missing in the payload")

        po = self.caffe_worker_client.predict(pi)

        if po.bo.status == 'Success':
            resp.status = falcon.HTTP_200
            resp.body = (str(po.values))
        elif po.bo.status == 'Failure':
            resp.body = json.dumps({'status': 'Failure', 'message' : 'Error occurred'})
            resp.status = falcon.HTTP_500
            raise falcon.HTTPInternalServerError('Internal Server Error', 'Predict failed! ')
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def on_get(self, req, resp):
        q = req.get_param('q')

        resp.content_type = 'text/plain; charset=utf-8'

        if not q:
            resp.body = 'Bad Request'
            resp.status = falcon.HTTP_400
            return

        try:
            zenline = zenlines[q]
        except KeyError:
            resp.body = 'Not Found'
            resp.status = falcon.HTTP_404
            return

        resp.body = zenline
        resp.status = falcon.HTTP_200
项目:CAL    作者:HPCC-Cloud-Computing    | 项目源码 | 文件源码
def test_process_request_failed_request_no_body(self):
        bad_headers = {
            'Content-Length': '0',
            'Content-Type': 'application/json',
            'URL-METHODS': 'POST, GET, PUT',
        }

        result = self.simulate_post(headers=bad_headers)
        self.assertEqual(falcon.HTTP_400, result.status)
项目:CAL    作者:HPCC-Cloud-Computing    | 项目源码 | 文件源码
def test_process_request_failed_request_MalformedJSON(self):
        headers = {
            'Content-Type': 'application/json',
            'URL-METHODS': 'POST, GET, PUT',
        }

        bad_body = '{"cloud":"cloud1"'
        result = self.simulate_post(headers=headers, body=bad_body)
        self.assertEqual(falcon.HTTP_400, result.status)
项目:MusicBot    作者:BjoernPetersen    | 项目源码 | 文件源码
def queue(body, remove: hug.types.boolean = False, user: hug.directives.user = None, response=None):
    try:
        song = Song.from_json(body, music_api_names)
        song.user = user['name']
    except ValueError as e:
        logger.debug("Received bad json %s", e)
        response.status = falcon.HTTP_400
        return str(e)

    def _remove():
        try:
            logger.debug("Song %s removed by %s", song, user['name'])
            queue.remove(song)
        except ValueError:
            logger.debug("%s tried to remove Song not in queue: %s", user['name'], song)
            response.status = falcon.HTTP_400
            return "song {} is not in queue".format(song)

    if remove:
        if not has_permission(user, ["admin", "mod", "queue_remove"]):
            try:
                queue_song = queue[queue.index(song)]
                if queue_song.user == user['name']:
                    logger.debug("User %s removes own song %s", user['name'], song)
                    _remove()
                    return "OK"
            except (ValueError, IndexError):
                pass
            logger.debug("Unauthorized attempt to remove song from queue by %s", user['name'])
            response.status = falcon.HTTP_FORBIDDEN
            return "Not permitted"
        _remove()
    else:
        logger.debug("Song %s added by %s", song, user['name'])
        queue.append(song)
    return "OK"
项目:MusicBot    作者:BjoernPetersen    | 项目源码 | 文件源码
def search(api_name, query, max_fetch: hug.types.number = 50, response=None):
    max_fetch = min(50, max(1, max_fetch))
    try:
        api = music_api_names[api_name]
    except KeyError:
        logger.debug("Tried to search on unknown API %s", api_name)
        response.status = falcon.HTTP_400
        return "Unknown API"

    if not query:
        response.status = falcon.HTTP_400
        return "Invalid query"

    return list(map(Song.to_json, api.search_song(query, max_fetch=max_fetch)))
项目:MusicBot    作者:BjoernPetersen    | 项目源码 | 文件源码
def move(moving_song_json, other_song_json, after_other: hug.types.boolean = False, user: hug.directives.user = None,
         response=None):
    """
    Move a song before or after another one.
    Needs mod permission.
    :param moving_song_json: the song to move
    :param other_song_json: the song to move before/after
    :param after_other: whether to move after the other song. Passing anything will be evaluated to true.
    """
    if not has_permission(user, ['admin', 'mod']):
        logger.debug("%s tried to move a song, but isn't allowed to.", user['name'])
        response.status = falcon.HTTP_FORBIDDEN
        return "Not a mod"

    try:
        moving_song = Song.from_json(moving_song_json, music_api_names)
        other_song = Song.from_json(other_song_json, music_api_names)
    except ValueError as e:
        logger.debug("Received invalid json (%s): %s , %s", str(e), moving_song_json, other_song_json)
        response.status = falcon.HTTP_400
        return str(e)

    try:
        queue.remove(moving_song)
    except ValueError:
        logger.debug("Tried to move song %s that wasn't in the queue", moving_song)
        response.status = falcon.HTTP_400
        return "song {} is not in queue".format(moving_song)

    try:
        index = queue.index(other_song)
        if after_other:
            index += 1
        queue.insert(index, moving_song)
        logger.debug("Moved song %s after/before(%s) %s", moving_song, after_other, other_song)
        return player_state()
    except ValueError:
        logger.debug("Couldn't move song %s, because other song %s was removed from queue", moving_song, other_song)
        response.status = falcon.HTTP_400
        return "song {} is not in queue".format(other_song)
项目:MusicBot    作者:BjoernPetersen    | 项目源码 | 文件源码
def grant_permission(target_username, body, user: hug.directives.user = None, response=None):
    """
    Grant a permission to a user
    Note that the new permissions only apply after the user logged out and in again.
    Needs admin permission.
    :param target_username: the username of the user the permission should be granted
    :param body: the permission as returned by get_permissions
    :return: 'OK', error message or None
    """
    try:
        permission = _Permission.from_json(body)
    except ValueError:
        response.status = falcon.HTTP_UNPROCESSABLE_ENTITY
        return "invalid JSON"
    if not is_admin(user):
        logger.debug("%s tried to grant a permission %s to %s but is not admin.", user['name'], permission,
                     target_username)
        response.status = falcon.HTTP_FORBIDDEN
        return None
    target_username = target_username.strip().lower()
    client = _get_client(target_username)
    if not client:
        logger.debug("%s tried to grant permission to unknown user %s", user['name'], target_username)
        response.status = falcon.HTTP_400
        return "unknown target user"
    permissions = client.permissions
    permissions.append(permission.name)
    permissions = list(set(permissions))
    db = _get_db_conn()
    try:
        with db:
            db.execute("UPDATE clients SET permissions=? WHERE username=?", [",".join(permissions), target_username])
    finally:
        db.close()
    return "OK"
项目:MusicBot    作者:BjoernPetersen    | 项目源码 | 文件源码
def revoke_permission(target_username, body, user: hug.directives.user = None, response=None):
    """
    Revokes a granted permission.
    Note that the new permissions only apply after the user logged out and in again.
    Needs admin permission.
    :param target_username: the username of the user whos permission should be revoked
    :param body: the permission as returned by get_permissions
    :return: 'OK' or error_message or None
    """
    try:
        permission = _Permission.from_json(body)
    except ValueError:
        response.status = falcon.HTTP_UNPROCESSABLE_ENTITY
        return "invalid JSON"
    if not is_admin(user):
        logger.debug("%s tried to revoke a permission %s from %s but is not admin.", user['name'], permission,
                     target_username)
        response.status = falcon.HTTP_FORBIDDEN
        return None
    target_username = target_username.strip().lower()
    client = _get_client(target_username)
    if not client:
        logger.debug("%s tried to revoke permission from unknown user %s", user['name'], target_username)
        response.status = falcon.HTTP_400
        return "unknown target user"
    permissions = client.permissions
    try:
        permissions.remove(permission.name)
    except ValueError:
        pass
    db = _get_db_conn()
    try:
        with db:
            db.execute("UPDATE clients SET permissions=? WHERE username=?", [",".join(permissions), target_username])
    finally:
        db.close()
    return "OK"
项目:MusicBot    作者:BjoernPetersen    | 项目源码 | 文件源码
def get_available_offline_playlists(user: hug.directives.user, response=None):
    """
    Get all available playlists of the offline API.
    :return: a list of playlists of the form {'playlist_id': <id>, 'playlist_name': <name>}
    """
    if not has_permission(user, ["admin", "mod", "select_playlist"]):
        response.status = falcon.HTTP_FORBIDDEN
        return "Forbidden"
    try:
        api = music_api_names['offline_api']
        playlists = api.get_available_playlists()
        return list(map(lambda p: {'playlist_id': p[0], 'playlist_name': p[1]}, playlists))
    except KeyError:
        response.status = falcon.HTTP_400
        return "Not in offline mode"
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def on_patch(self, req, resp):
        raise falcon.HTTPError(falcon.HTTP_400)
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def test_no_description_json(self, client):
        response = client.simulate_patch('/fail')
        assert response.status == falcon.HTTP_400
        assert response.json == {'title': '400 Bad Request'}
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def test_no_description_xml(self, client):
        response = client.simulate_patch(
            path='/fail', headers={'Accept': 'application/xml'}
        )
        assert response.status == falcon.HTTP_400

        expected_xml = (b'<?xml version="1.0" encoding="UTF-8"?><error>'
                        b'<title>400 Bad Request</title></error>')

        assert response.content == expected_xml
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def test_invalid_header(self, client):
        client.app.add_route('/400', InvalidHeaderResource())
        response = client.simulate_request(path='/400')

        expected_desc = (u'The value provided for the X-Auth-Token '
                         u'header is invalid. Please provide a valid token.')

        expected_body = {
            u'title': u'Invalid header value',
            u'description': expected_desc,
            u'code': u'A1001',
        }

        assert response.status == falcon.HTTP_400
        assert response.json == expected_body
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def test_missing_header(self, client):
        client.app.add_route('/400', MissingHeaderResource())
        response = client.simulate_request(path='/400')

        expected_body = {
            u'title': u'Missing header value',
            u'description': u'The X-Auth-Token header is required.',
        }

        assert response.status == falcon.HTTP_400
        assert response.json == expected_body
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def test_missing_param(self, client):
        client.app.add_route('/400', MissingParamResource())
        response = client.simulate_request(path='/400')

        expected_body = {
            u'title': u'Missing parameter',
            u'description': u'The "id" parameter is required.',
            u'code': u'P1003',
        }

        assert response.status == falcon.HTTP_400
        assert response.json == expected_body
项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def test_misc(self, client):
        self._misc_test(client, falcon.HTTPBadRequest, falcon.HTTP_400)
        self._misc_test(client, falcon.HTTPNotAcceptable, falcon.HTTP_406,
                        needs_title=False)
        self._misc_test(client, falcon.HTTPConflict, falcon.HTTP_409)
        self._misc_test(client, falcon.HTTPPreconditionFailed, falcon.HTTP_412)
        self._misc_test(client, falcon.HTTPUnsupportedMediaType, falcon.HTTP_415,
                        needs_title=False)
        self._misc_test(client, falcon.HTTPUnprocessableEntity, falcon.HTTP_422)
        self._misc_test(client, falcon.HTTPUnavailableForLegalReasons, falcon.HTTP_451,
                        needs_title=False)
        self._misc_test(client, falcon.HTTPInternalServerError, falcon.HTTP_500)
        self._misc_test(client, falcon.HTTPBadGateway, falcon.HTTP_502)
项目:drydock    作者:att-comdev    | 项目源码 | 文件源码
def on_post(self, req, resp):
        """Method handler for POST requests.

        :param req: Falcon request object
        :param resp: Falcon response object
        """
        try:
            json_data = self.req_json(req)
            design = None
            if json_data is not None:
                base_design = json_data.get('base_design_id', None)

                if base_design is not None:
                    base_design = uuid.UUID(base_design)
                    design = hd_objects.SiteDesign(base_design_id=base_design)
            else:
                design = hd_objects.SiteDesign()
            design.assign_id()
            design.create(req.context, self.state_manager)

            resp.body = json.dumps(design.obj_to_simple())
            resp.status = falcon.HTTP_201
        except errors.StateError:
            self.error(req.context, "Error updating persistence")
            self.return_error(
                resp,
                falcon.HTTP_500,
                message="Error updating persistence",
                retry=True)
        except errors.InvalidFormat as fex:
            self.error(req.context, str(fex))
            self.return_error(
                resp, falcon.HTTP_400, message=str(fex), retry=False)
项目:drydock    作者:att-comdev    | 项目源码 | 文件源码
def on_post(self, req, resp):
        """Handler for POST method."""
        # A map of supported actions to the handlers for tasks for those actions
        supported_actions = {
            'validate_design': TasksResource.task_validate_design,
            'verify_site': TasksResource.task_verify_site,
            'prepare_site': TasksResource.task_prepare_site,
            'verify_nodes': TasksResource.task_verify_nodes,
            'prepare_nodes': TasksResource.task_prepare_nodes,
            'deploy_nodes': TasksResource.task_deploy_nodes,
            'destroy_nodes': TasksResource.task_destroy_nodes,
        }

        try:
            json_data = self.req_json(req)

            action = json_data.get('action', None)
            if supported_actions.get(action, None) is None:
                self.error(req.context, "Unsupported action %s" % action)
                self.return_error(
                    resp,
                    falcon.HTTP_400,
                    message="Unsupported action %s" % action,
                    retry=False)
            else:
                supported_actions.get(action)(self, req, resp, json_data)
        except Exception as ex:
            self.error(req.context, "Unknown error: %s\n%s" %
                       (str(ex), traceback.format_exc()))
            self.return_error(
                resp, falcon.HTTP_500, message="Unknown error", retry=False)
项目:monasca-events-api    作者:openstack    | 项目源码 | 文件源码
def test_should_fail_empty_body(self, bulk_processor):
        events_resource = _init_resource(self)
        events_resource._processor = bulk_processor
        self.simulate_request(
            path=ENDPOINT,
            method='POST',
            headers={
                'Content-Type': 'application/json',
                'X_ROLES': 'monasca'
            },
            body=''
        )
        self.assertEqual(falcon.HTTP_400, self.srmock.status)
项目:monasca-events-api    作者:openstack    | 项目源码 | 文件源码
def test_request_for_incorrect_version(self):
        incorrect_version = 'v2.0'
        uri = _get_versioned_url(incorrect_version)

        self.simulate_request(
            uri,
            method='GET',
            headers={
                'Content-Type': 'application/json'
            }
        )

        self.assertEqual(falcon.HTTP_400, self.srmock.status)
项目:ckb-water-vapor    作者:Drummersbrother    | 项目源码 | 文件源码
def cmd_post_rgb_change_single(self, req, resp, post_params):
        """This method handles changing the keys of the keyboard to a single colour."""

        # We check if all arguments exist
        if post_params["arguments"]["key"] and post_params["arguments"]["color"]:
            if self.is_hex_color(post_params["arguments"]["color"]):

                # We check if the command executed successfully
                if self.keyboard.set_key_color(post_params["arguments"]["key"], (
                        int(post_params["arguments"]["color"][:2], base=16),
                        int(post_params["arguments"]["color"][2:4], base=16),
                        int(post_params["arguments"]["color"][4:], base=16))):
                    # Successfully executed the command
                    resp.status = falcon.HTTP_200
                    resp.body = json.dumps({"message": "Command successfully executed"})

                    return

                else:
                    # Invalid arguments
                    resp.status = falcon.HTTP_400
                    resp.body = json.dumps({"message": "Invalid arguments"})

            else:
                # Invalid arguments
                resp.status = falcon.HTTP_400
                resp.body = json.dumps({"message": "Invalid arguments"})

        else:
            # Invalid arguments
            resp.status = falcon.HTTP_400
            resp.body = json.dumps({"message": "Invalid arguments"})
项目:promenade    作者:att-comdev    | 项目源码 | 文件源码
def on_post(self, req, resp):
        href = req.get_param('href', required=True)
        try:
            config = Configuration.from_design_ref(href)
            validation.check_design(config)
            msg = "Promenade validations succeeded"
            return self._return_msg(resp, falcon.HTTP_200, message=msg)
        except exceptions.ValidationException as e:
            msg = "Promenade validations failed: %s" % str(e)
            return self._return_msg(
                resp, falcon.HTTP_400, status="Invalid", message=msg)
项目:Cuppa    作者:flipkart-incubator    | 项目源码 | 文件源码
def on_get(self, req, resp):
        """Handles GET requests"""
        model_type = req.get_param('model-type')
        resp.status = falcon.HTTP_200  # This is the default status
        if model_type:
            resp.body = str(self.load_balancer.get_model_to_workers_list(model_type))
        else:
            resp.status = falcon.HTTP_400
            raise falcon.HTTPBadRequest("Bad Request", "model-type is missing in query params")
项目:metricsandstuff    作者:bucknerns    | 项目源码 | 文件源码
def bad_request(message):
        raise falcon.HTTPBadRequest(
            description=message, title=falcon.HTTP_400, code=400)
项目:commissaire-mvp    作者:projectatomic    | 项目源码 | 文件源码
def on_put(self, req, resp, address):
        """
        Handles the creation of a new Host.

        :param req: Request instance that will be passed through.
        :type req: falcon.Request
        :param resp: Response instance that will be passed through.
        :type resp: falcon.Response
        :param address: The address of the Host being requested.
        :type address: str
        """
        try:
            # Extract what we need from the input data.
            # Don't treat it as a skeletal host record.
            req_data = req.stream.read()
            req_body = json.loads(req_data.decode())
            ssh_priv_key = req_body['ssh_priv_key']
            # Remote user is optional.
            remote_user = req_body.get('remote_user', 'root')
            # Cluster member is optional.
            cluster_name = req_body.get('cluster', None)
        except (KeyError, ValueError):
            self.logger.info(
                'Bad client PUT request for host {0}: {1}'.
                format(address, req_data))
            resp.status = falcon.HTTP_400
            return

        resp.status, host_model = util.etcd_host_create(
            address, ssh_priv_key, remote_user, cluster_name)

        req.context['model'] = host_model
项目:commissaire-mvp    作者:projectatomic    | 项目源码 | 文件源码
def on_put(self, req, resp):
        """
        Handles the creation of a new Host.

        :param req: Request instance that will be passed through.
        :type req: falcon.Request
        :param resp: Response instance that will be passed through.
        :type resp: falcon.Response
        """
        try:
            address = req.env['REMOTE_ADDR']
        except KeyError:
            self.logger.info('Unable to determine host address')
            resp.status = falcon.HTTP_400
            return

        try:
            # Extract what we need from the input data.
            # Don't treat it as a skeletal host record.
            req_data = req.stream.read()
            req_body = json.loads(req_data.decode())
            ssh_priv_key = req_body['ssh_priv_key']
            # Remote user is optional.
            remote_user = req_body.get('remote_user', 'root')
            # Cluster member is optional.
            cluster_name = req_body.get('cluster', None)
        except (KeyError, ValueError):
            self.logger.info(
                'Bad client PUT request for host {0}: {1}'.
                format(address, req_data))
            resp.status = falcon.HTTP_400
            return

        resp.status, host_model = util.etcd_host_create(
            address, ssh_priv_key, remote_user, cluster_name)

        req.context['model'] = host_model
项目:drydock    作者:att-comdev    | 项目源码 | 文件源码
def on_post(self, req, resp):

        # create resp message
        resp_message = {
            'kind': 'Status',
            'apiVersion': 'v1',
            'metaData': {},
            'status': '',
            'message': '',
            'reason': 'Validation',
            'details': {
                'errorCount': 0,
                'messageList': []
            },
            'code': '',
        }

        try:
            json_data = self.req_json(req)

            if json_data is None:
                resp.status = falcon.HTTP_400
                err_message = 'Request body must not be empty for validation.'
                self.error(req.context, err_message)
                return self.return_error(resp, falcon.HTTP_400, err_message)

            design_ref = json_data.get('href', None)

            if not design_ref:
                resp.status = falcon.HTTP_400
                err_message = 'The "href" key must be provided in the request body.'
                self.error(req.context, err_message)
                return self.return_error(resp, falcon.HTTP_400, err_message)

            message, design_data = self.orchestrator.get_effective_site(
                design_ref)

            resp_message['details']['errorCount'] = message.error_count
            resp_message['details']['messageList'] = [m.to_dict() for m in message.message_list]

            if message.error_count == 0:
                resp_message['status'] = 'Valid'
                resp_message['message'] = 'Drydock Validations succeeded'
                resp_message['code'] = 200
                resp.status = falcon.HTTP_200
                resp.body = json.dumps(resp_message)
            else:
                resp_message['status'] = 'Invalid'
                resp_message['message'] = 'Drydock Validations failed'
                resp_message['code'] = 400
                resp.status = falcon.HTTP_400
                resp.body = json.dumps(resp_message)

        except errors.InvalidFormat as e:
            err_message = str(e)
            resp.status = falcon.HTTP_400
            self.error(req.context, err_message)
            self.return_error(resp, falcon.HTTP_400, err_message)
项目:drydock    作者:att-comdev    | 项目源码 | 文件源码
def on_post(self, req, resp, design_id):
        ingester_name = req.params.get('ingester', None)

        if ingester_name is None:
            self.error(
                None,
                "DesignsPartsResource POST requires parameter 'ingester'")
            self.return_error(
                resp,
                falcon.HTTP_400,
                message="POST requires parameter 'ingester'",
                retry=False)
        else:
            try:
                raw_body = req.stream.read(req.content_length or 0)
                if raw_body is not None and len(raw_body) > 0:
                    parsed_items = self.ingester.ingest_data(
                        plugin_name=ingester_name,
                        design_state=self.state_manager,
                        content=raw_body,
                        design_id=design_id,
                        context=req.context)
                    resp.status = falcon.HTTP_201
                    resp.body = json.dumps(
                        [x.obj_to_simple() for x in parsed_items])
                else:
                    self.return_error(
                        resp,
                        falcon.HTTP_400,
                        message="Empty body not supported",
                        retry=False)
            except ValueError:
                self.return_error(
                    resp,
                    falcon.HTTP_500,
                    message="Error processing input",
                    retry=False)
            except LookupError:
                self.return_error(
                    resp,
                    falcon.HTTP_400,
                    message="Ingester %s not registered" % ingester_name,
                    retry=False)
项目:ckb-water-vapor    作者:Drummersbrother    | 项目源码 | 文件源码
def on_get(self, req, resp):
        """This method handles all get requests to our API."""

        # The requester has to be able to accept json
        if req.client_accepts_json:

            # We check if the user used a command or not
            if req.content_length in (0, None):
                # Everything went ok
                resp.status = falcon.HTTP_200

                # We return the string representation of the keyboard
                resp.body = json.dumps({"keyboard": str(self.keyboard)})

            else:
                # We check if the user want/tries to use a command
                try:
                    # Store the request body
                    req_body = req.stream.read().decode("utf-8")

                    # We try to parse the request as json
                    post_params = json.loads(req_body)

                    # We check that the arguments exist and are valid
                    if post_params["command"]:
                        # We check what command was used
                        for command in self.get_commands:
                            # We check if the current request matches the command
                            if post_params["command"] == command["command"]:
                                # We call the command method with the request object, response object, and the parsed request dictionary
                                command["method"](req, resp, post_params)

                                # No more than one command shall be executed per request
                                break
                        else:
                            # If no command was found we return bad request
                            resp.status = falcon.HTTP_400
                            resp.body = json.dumps({"message": "Invalid command"})

                    else:
                        # Invalid arguments
                        resp.status = falcon.HTTP_400
                        resp.body = json.dumps({"message": "Invalid arguments"})

                    # We're done now
                    return

                except json.JSONDecodeError:
                    resp.status = falcon.HTTP_400
                    resp.body = json.dumps({"message": "Invalid JSON"})
        else:
            # Fuck you user
            resp.status = falcon.HTTP_417
            resp.body = json.dumps({"message": "Client doesn't accept JSON"})
项目:ckb-water-vapor    作者:Drummersbrother    | 项目源码 | 文件源码
def on_post(self, req, resp):
        """This method handles all post requests to our API."""

        # The requester has to be able to accept json
        if req.client_accepts_json:

            try:
                if req.content_length in (0, None):
                    raise json.JSONDecodeError

                # We store the request body
                req_body = req.stream.read().decode("utf-8")

                # We try to parse the request as json
                post_params = json.loads(req_body)

                # We check that the arguments exist and are valid
                if post_params["command"]:
                    # We check what command was used
                    for command in self.post_commands:
                        # We check if the current request matches the command
                        if post_params["command"] == command["command"]:
                            # We call the command method with the request object, response object, and the parsed request dictionary
                            command["method"](req, resp, post_params)

                            # No more than one command shall be executed per request
                            break
                    else:
                        # If no command was found we return bad request
                        resp.status = falcon.HTTP_400
                        resp.body = json.dumps({"message": "Invalid command"})

                else:
                    # Invalid arguments
                    resp.status = falcon.HTTP_400
                    resp.body = json.dumps({"message": "Invalid arguments"})

                # We're done now
                return

            except json.JSONDecodeError:
                resp.status = falcon.HTTP_400
                resp.body = json.dumps({"message": "Invalid JSON"})

        else:
            # Fuck you user
            resp.status = falcon.HTTP_417
项目:geonymapi    作者:geonym    | 项目源码 | 文件源码
def getGeonym(self, req, resp, query=None):
        resp.status = falcon.HTTP_200
        geo = None

        # projections utilisées pour transformation en WGS84/Lambert93
        s_srs = Proj(init='EPSG:2154')
        t_srs = Proj(init='EPSG:4326')

        if 'x' in req.params and 'y' in req.params:
            lon,lat = transform(s_srs,t_srs,req.params['x'],req.params['y'])
            query = geonym.ll2geonym(lat, lon)
        elif 'lat' in req.params and 'lon' in req.params:
            query = geonym.ll2geonym(float(req.params['lat']), float(req.params['lon']))
        elif 'geonym' in req.params:
            query = req.params['geonym']
        elif 'adresse' in req.params:
            r = requests.get(URL_GEOCODER+'/search', params={"q":req.params['adresse'], "autocomplete":0, "limit":1}, timeout=1)
            geo = json.loads(r.text)
            geo['source']=URL_GEOCODER
            query = geonym.ll2geonym(geo['features'][0]['geometry']['coordinates'][1], geo['features'][0]['geometry']['coordinates'][0])

        if query is not None and geonym.checkGeonym(query):
            rev = None
            data = geonym.geonym2ll(query)
            if 'reverse' in req.params and req.params['reverse']=='yes':
                r = requests.get(URL_GEOCODER+'/reverse', params={"lat":data['lat'],"lon":data['lon'],"limit":1}, timeout=1)
                if r.status_code == 200:
                    rev = json.loads(r.text)
                    rev['source']=URL_GEOCODER

            x,y = transform(t_srs,s_srs,data['lon'],data['lat'])
            # on ne retourne les coordonnées Lambert que si on est en zone Lambert93
            if y > -357823.2365 and x > 6037008.6939 and y < 1313632.3628 and x< 7230727.3772:
                data['x'] = int(x)
                data['y'] = int(y)

            data['checksum'] = geonym.checksum(query)

            geojson = {"type":"Feature",
                "properties":data,
                "link": "http://www.geonym.fr/visu/?g=%s" % (geonym.cleanGeonym(query),),
                "params":geonym.getParams(),
                "geometry":{"type":"Polygon","coordinates":[[[data['west'],data['south']],[data['east'],data['south']],[data['east'],data['north']],[data['west'],data['north']],[data['west'],data['south']]]]}}
            if rev is not None:
                geojson['reverse'] = rev
            if geo is not None:
                geojson['geocode'] = geo
            resp.body = json.dumps(geojson, sort_keys=True, indent=4, separators=(',', ': '))
            resp.set_header('Content-type','application/json')
        else:
            geojson = {
                "type": "Feature",
                "link": "https://github.com/geonym/geonymapi",
                "params": geonym.getParams()
            }
            resp.status = falcon.HTTP_400
            resp.set_header('Content-type', 'application/json')
            resp.body = json.dumps(
                geojson, sort_keys=True, indent=4, separators=(',', ': '))
项目:commissaire-mvp    作者:projectatomic    | 项目源码 | 文件源码
def test_cluster_hosts_overwrite(self):
        """
        Verify overwriting a cluster host list.
        """
        with mock.patch('cherrypy.engine.publish') as _publish:
            manager = mock.MagicMock(StoreHandlerManager)
            _publish.return_value = [manager]

            # Verify setting host list works with a proper request
            manager.get.return_value = make_new(CLUSTER_WITH_FLAT_HOST)
            body = self.simulate_request(
                '/api/v0/cluster/development/hosts', method='PUT',
                body='{"old": ["10.2.0.2"], "new": ["10.2.0.2", "10.2.0.3"]}')
            self.assertEqual(falcon.HTTP_200, self.srmock.status)
            self.assertEqual({}, json.loads(body[0]))

            # Verify bad request (KeyError) returns the proper result
            manager.get.side_effect = KeyError
            body = self.simulate_request(
                '/api/v0/cluster/development/hosts', method='PUT',
                body='{"new": ["10.2.0.2", "10.2.0.3"]}')
            self.assertEqual(falcon.HTTP_400, self.srmock.status)
            self.assertEqual({}, json.loads(body[0]))

            # Verify bad request (TypeError) returns the proper result
            manager.get.side_effect = TypeError
            body = self.simulate_request(
                '/api/v0/cluster/development/hosts', method='PUT',
                body='["10.2.0.2", "10.2.0.3"]')
            self.assertEqual(falcon.HTTP_400, self.srmock.status)
            self.assertEqual({}, json.loads(body[0]))

            # Verify bad cluster name returns the proper result
            manager.get.side_effect = Exception
            body = self.simulate_request(
                '/api/v0/cluster/bogus/hosts', method='PUT',
                body='{"old": ["10.2.0.2"], "new": ["10.2.0.2", "10.2.0.3"]}')
            self.assertEqual(falcon.HTTP_404, self.srmock.status)
            self.assertEqual({}, json.loads(body[0]))

            # Verify host list conflict returns the proper result
            manager.get.side_effect = None
            body = self.simulate_request(
                '/api/v0/cluster/development/hosts', method='PUT',
                body='{"old": [], "new": ["10.2.0.2", "10.2.0.3"]}')
            self.assertEqual(falcon.HTTP_409, self.srmock.status)
            self.assertEqual({}, json.loads(body[0]))
项目:commissaire-mvp    作者:projectatomic    | 项目源码 | 文件源码
def on_put(self, req, resp, name):
        """
        Handles PUT requests for Cluster hosts.
        This replaces the entire host list for a Cluster.

        :param req: Request instance that will be passed through.
        :type req: falcon.Request
        :param resp: Response instance that will be passed through.
        :type resp: falcon.Response
        :param name: The name of the Cluster being requested.
        :type name: str
        """
        try:
            req_body = json.loads(req.stream.read().decode())
            old_hosts = set(req_body['old'])  # Ensures no duplicates
            new_hosts = set(req_body['new'])  # Ensures no duplicates
        except (KeyError, TypeError):
            self.logger.info(
                'Bad client PUT request for cluster "{0}": {1}'.
                format(name, req_body))
            resp.status = falcon.HTTP_400
            return

        try:
            store_manager = cherrypy.engine.publish('get-store-manager')[0]
            cluster = store_manager.get(Cluster.new(name=name))
        except:
            resp.status = falcon.HTTP_404
            return

        # old_hosts must match current hosts to accept new_hosts.
        if old_hosts != set(cluster.hostset):
            self.logger.info(
                'Conflict setting hosts for cluster {0}'.format(name))
            self.logger.debug('{0} != {1}'.format(old_hosts, cluster.hostset))
            resp.status = falcon.HTTP_409
            return

        # FIXME: Need input validation.  For each new host,
        #        - Does the host exist at /commissaire/hosts/{IP}?
        #        - Does the host already belong to another cluster?

        # FIXME: Should guard against races here, since we're fetching
        #        the cluster record and writing it back with some parts
        #        unmodified.  Use either locking or a conditional write
        #        with the etcd 'modifiedIndex'.  Deferring for now.

        cluster.hostset = list(new_hosts)
        store_manager.save(cluster)
        resp.status = falcon.HTTP_200
项目:commissaire-mvp    作者:projectatomic    | 项目源码 | 文件源码
def on_put(self, req, resp, name):
        """
        Handles the creation of a new Network.

        :param req: Request instance that will be passed through.
        :type req: falcon.Request
        :param resp: Response instance that will be passed through.
        :type resp: falcon.Response
        :param name: The friendly name of the network.
        :type address: str
        """
        try:
            req_data = req.stream.read()
            req_body = json.loads(req_data.decode())
            network_type = req_body['type']
            options = req_body.get('options', {})
        except (KeyError, ValueError):
            self.logger.info(
                'Bad client PUT request for network {0}: {1}'.
                format(name, req_data))
            resp.status = falcon.HTTP_400
            return

        store_manager = cherrypy.engine.publish('get-store-manager')[0]
        # If the type is flannel_etcd yet we have not etcd backend configured
        # don't create and notify the caller
        if network_type == C.NETWORK_TYPE_FLANNEL_ETCD:
            backend_found = False
            for handler_type, _, _ in store_manager.list_store_handlers():
                if handler_type is EtcdStoreHandler:
                    backend_found = True
                    break

            if not backend_found:
                self.logger.info(
                    'Network {0} can not be created as type flannel_etcd '
                    'as no etcd backend is configured.'.format(name))
                resp.status = falcon.HTTP_CONFLICT
                return

        network = Network.new(name=name, type=network_type, options=options)
        self.logger.debug('Saving network: {0}'.format(network.to_json()))
        store_manager.save(network)

        resp.status = falcon.HTTP_CREATED
        req.context['model'] = network