Python falcon.HTTP_BAD_REQUEST Examples

The following are 8 code examples of falcon.HTTP_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 falcon , or try the search function .
Example #1
Source File: test_validators.py    From falcon-boilerplate with MIT License 6 votes vote down vote up
def test_both_schemas_validation_failure():
    with pytest.raises(HTTPError) as excinfo:
        Resource().both_validated(GoodData(), BadData())

    assert excinfo.value.title == falcon.HTTP_INTERNAL_SERVER_ERROR
    assert excinfo.value.description == "Response data failed validation"

    with pytest.raises(HTTPError) as excinfo:
        Resource().both_validated(BadData(), GoodData())

    msg = "Request data failed validation: data must contain ['message'] properties"
    assert excinfo.value.title == falcon.HTTP_BAD_REQUEST
    assert excinfo.value.description == msg

    client = testing.TestClient(falcon.API())
    client.app.add_route("/test", Resource())
    result = client.simulate_put("/test", json=BadData.media)
    assert result.status_code == 400 
Example #2
Source File: handlers.py    From Python-Journey-from-Novice-to-Expert with MIT License 5 votes vote down vote up
def on_post(self, req, resp):
        self.process_request(req, resp)

        password = req.context.get('_body', {}).get('password')
        if password is None:
            resp.status = falcon.HTTP_BAD_REQUEST
            return None

        result = self.parse_password(password)
        resp.body = json.dumps(result) 
Example #3
Source File: test_generic.py    From graceful with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_create_bulk_without_list_results_in_bad_request(self):
        self.do_create_bulk(
            {'writable': 'changed', 'unsigned': 12}
        )
        assert self.srmock.status == falcon.HTTP_BAD_REQUEST


# actual test case classes here 
Example #4
Source File: util.py    From falcon-boilerplate with MIT License 5 votes vote down vote up
def retrieve_obj(id_: str, mapper_: Mapper) -> Model:
    name = mapper_.__class__.__name__.lower().split("mapper")[0].capitalize()
    obj = mapper_.get(id_)

    if obj is None:
        raise HTTPError(falcon.HTTP_BAD_REQUEST, f"{name} not found")
    elif obj.deleted_at is not None:
        raise HTTPError(falcon.HTTP_GONE, f"{name} was deleted")

    return obj 
Example #5
Source File: jsonschema.py    From falcon-boilerplate with MIT License 5 votes vote down vote up
def _validate(req_schema: Dict = None, resp_schema: Dict = None):
    def decorator(func):
        @wraps(func)
        def wrapper(self, req, resp, *args, **kwargs):
            if req_schema is not None:
                try:
                    schema = fastjsonschema.compile(req_schema)
                    schema(req.media)
                except fastjsonschema.JsonSchemaException as e:
                    msg = "Request data failed validation: {}".format(e.message)
                    raise HTTPError(falcon.HTTP_BAD_REQUEST, msg)

            result = func(self, req, resp, *args, **kwargs)

            if resp_schema is not None:
                try:
                    schema = fastjsonschema.compile(resp_schema)
                    schema(resp.media)
                except fastjsonschema.JsonSchemaException:
                    raise HTTPError(
                        falcon.HTTP_INTERNAL_SERVER_ERROR,
                        "Response data failed validation",
                    )
                    # Do not return 'e.message' in the response to
                    # prevent info about possible internal response
                    # formatting bugs from leaking out to users.

            return result

        return wrapper

    return decorator 
Example #6
Source File: test_validators.py    From falcon-boilerplate with MIT License 5 votes vote down vote up
def test_req_schema_validation_failure():
    with pytest.raises(falcon.HTTPError) as excinfo:
        Resource().request_validated(BadData(), None)

    msg = "Request data failed validation: data must contain ['message'] properties"
    assert excinfo.value.title == falcon.HTTP_BAD_REQUEST
    assert excinfo.value.description == msg 
Example #7
Source File: harvester.py    From polkascan-pre-harvester with GNU General Public License v3.0 4 votes vote down vote up
def on_post(self, req, resp):

        block_hash = None

        if req.media.get('block_id'):
            substrate = SubstrateInterface(SUBSTRATE_RPC_URL)
            block_hash = substrate.get_block_hash(req.media.get('block_id'))
        elif req.media.get('block_hash'):
            block_hash = req.media.get('block_hash')
        else:
            resp.status = falcon.HTTP_BAD_REQUEST
            resp.media = {'errors': ['Either block_hash or block_id should be supplied']}

        if block_hash:
            print('Processing {} ...'.format(block_hash))
            harvester = PolkascanHarvesterService(
                db_session=self.session,
                type_registry=TYPE_REGISTRY,
                type_registry_file=TYPE_REGISTRY_FILE
            )

            block = Block.query(self.session).filter(Block.hash == block_hash).first()

            if block:
                resp.status = falcon.HTTP_200
                resp.media = {'result': 'already exists', 'parentHash': block.parent_hash}
            else:

                amount = req.media.get('amount', 1)

                for nr in range(0, amount):
                    try:
                        block = harvester.add_block(block_hash)
                    except BlockAlreadyAdded as e:
                        print('Skipping {}'.format(block_hash))
                    block_hash = block.parent_hash
                    if block.id == 0:
                        break

                self.session.commit()

                resp.status = falcon.HTTP_201
                resp.media = {'result': 'added', 'parentHash': block.parent_hash}

        else:
            resp.status = falcon.HTTP_404
            resp.media = {'result': 'Block not found'} 
Example #8
Source File: harvester.py    From polkascan-pre-harvester with GNU General Public License v3.0 4 votes vote down vote up
def on_post(self, req, resp):

        block_hash = None

        if 'block_id' in req.media:
            block = Block.query(self.session).filter(Block.id == req.media.get('block_id')).first()
        elif req.media.get('block_hash'):
            block_hash = req.media.get('block_hash')
            block = Block.query(self.session).filter(Block.hash == block_hash).first()
        else:
            block = None
            resp.status = falcon.HTTP_BAD_REQUEST
            resp.media = {'errors': ['Either block_hash or block_id should be supplied']}

        if block:
            print('Sequencing #{} ...'.format(block.id))

            harvester = PolkascanHarvesterService(
                db_session=self.session,
                type_registry=TYPE_REGISTRY,
                type_registry_file=TYPE_REGISTRY_FILE
            )

            if block.id == 1:
                # Add genesis block
                parent_block = harvester.add_block(block.parent_hash)

            block_total = BlockTotal.query(self.session).filter_by(id=block.id).first()
            parent_block = Block.query(self.session).filter(Block.id == block.id - 1).first()
            parent_block_total = BlockTotal.query(self.session).filter_by(id=block.id - 1).first()

            if block_total:
                resp.status = falcon.HTTP_200
                resp.media = {'result': 'already exists', 'blockId': block.id}
            else:

                if parent_block_total:
                    parent_block_total = parent_block_total.asdict()

                if parent_block:
                    parent_block = parent_block.asdict()

                harvester.sequence_block(block, parent_block, parent_block_total)

                self.session.commit()

                resp.status = falcon.HTTP_201
                resp.media = {'result': 'added', 'parentHash': block.parent_hash}

        else:
            resp.status = falcon.HTTP_404
            resp.media = {'result': 'Block not found'}