Пример #1
0
    async def action_handler(service, action_type, payload, props, **kwds):
        # if the payload represents a new instance of `model`
        if action_type == get_crud_action('read', name or Model):
            # the props of the message
            message_props = {}
            # if there was a correlation id in the request
            if 'correlation_id' in props:
                # make sure it ends up in the reply
                message_props['correlation_id'] = props['correlation_id']

            try:
                # resolve the query using the service schema
                resolved = service.schema.execute(payload)
                # create the string response
                response = json.dumps({
                    'data': {key:value for key,value in resolved.data.items()},
                    'errors': resolved.errors
                })

                # publish the success event
                await service.event_broker.send(
                    payload=response,
                    action_type=change_action_status(action_type, success_status()),
                    **message_props
                )

            # if something goes wrong
            except Exception as err:
                # publish the error as an event
                await service.event_broker.send(
                    payload=str(err),
                    action_type=change_action_status(action_type, error_status()),
                    **message_props
                )
Пример #2
0
    async def action_handler(service,
                             action_type,
                             payload,
                             props,
                             notify=True,
                             **kwds):
        # if the payload represents a new instance of `Model`
        if action_type == get_crud_action('create', name or Model):
            # print('handling create for ' + name or Model)
            try:
                # the props of the message
                message_props = {}
                # if there was a correlation id in the request
                if 'correlation_id' in props:
                    # make sure it ends up in the reply
                    message_props['correlation_id'] = props['correlation_id']

                # for each required field
                for requirement in Model.required_fields():

                    # save the name of the field
                    field_name = requirement.name
                    # ensure the value is in the payload
                    # TODO: check all required fields rather than failing on the first
                    if not field_name in payload and field_name != 'id':
                        # yell loudly
                        raise ValueError(
                            "Required field not found in payload: %s" %
                            field_name)

                # create a new model
                new_model = Model(**payload)

                # save the new model instance
                new_model.save()

                # if we need to tell someone about what happened
                if notify:
                    # publish the scucess event
                    await service.event_broker.send(
                        payload=ModelSerializer().serialize(new_model),
                        action_type=change_action_status(
                            action_type, success_status()),
                        **message_props)

            # if something goes wrong
            except Exception as err:
                # if we need to tell someone about what happened
                if notify:
                    # publish the error as an event
                    await service.event_broker.send(
                        payload=str(err),
                        action_type=change_action_status(
                            action_type, error_status()),
                        **message_props)
                # otherwise we aren't supposed to notify
                else:
                    # raise the exception normally
                    raise err
Пример #3
0
    async def action_handler(service, action_type, payload, props, notify=True, **kwds):
        # if the payload represents a new instance of `Model`
        if action_type == get_crud_action('update', name or Model):
            try:
                # the props of the message
                message_props = {}
                # if there was a correlation id in the request
                if 'correlation_id' in props:
                    # make sure it ends up in the reply
                    message_props['correlation_id'] = props['correlation_id']


                # grab the nam eof the primary key for the model
                pk_field = Model.primary_key()

                # make sure there is a primary key to id the model
                if not pk_field.name in payload:
                    # yell loudly
                    raise ValueError("Must specify the pk of the model when updating")

                # grab the matching model
                model = Model.select().where(pk_field == payload[pk_field.name]).get()

                # remove the key from the payload
                payload.pop(pk_field.name, None)

                # for every key,value pair
                for key, value in payload.items():
                    # TODO: add protection for certain fields from being
                    # changed by the api
                    setattr(model, key, value)

                # save the updates
                model.save()

                # if we need to tell someone about what happened
                if notify:
                    # publish the scucess event
                    await service.event_broker.send(
                        payload=ModelSerializer().serialize(model),
                        action_type=change_action_status(action_type, success_status()),
                        **message_props
                    )

            # if something goes wrong
            except Exception as err:
                # if we need to tell someone about what happened
                if notify:
                    # publish the error as an event
                    await service.event_broker.send(
                        payload=str(err),
                        action_type=change_action_status(action_type, error_status()),
                        **message_props
                    )
                # otherwise we aren't supposed to notify
                else:
                    # raise the exception normally
                    raise err
Пример #4
0
    async def action_handler(service, action_type, payload, props, notify=True, **kwds):
        # if the payload represents a new instance of `Model`
        if action_type == get_crud_action('create', name or Model):
            # print('handling create for ' + name or Model)
            try:
                # the props of the message
                message_props = {}
                # if there was a correlation id in the request
                if 'correlation_id' in props:
                    # make sure it ends up in the reply
                    message_props['correlation_id'] = props['correlation_id']

                # for each required field
                for requirement in Model.required_fields():

                    # save the name of the field
                    field_name = requirement.name
                    # ensure the value is in the payload
                    # TODO: check all required fields rather than failing on the first
                    if not field_name in payload and field_name != 'id':
                        # yell loudly
                        raise ValueError(
                            "Required field not found in payload: %s" %field_name
                        )

                # create a new model
                new_model = Model(**payload)

                # save the new model instance
                new_model.save()

                # if we need to tell someone about what happened
                if notify:
                    # publish the scucess event
                    await service.event_broker.send(
                        payload=ModelSerializer().serialize(new_model),
                        action_type=change_action_status(action_type, success_status()),
                        **message_props
                    )

            # if something goes wrong
            except Exception as err:
                # if we need to tell someone about what happened
                if notify:
                    # publish the error as an event
                    await service.event_broker.send(
                        payload=str(err),
                        action_type=change_action_status(action_type, error_status()),
                        **message_props
                    )
                # otherwise we aren't supposed to notify
                else:
                    # raise the exception normally
                    raise err
Пример #5
0
    async def action_handler(service,
                             action_type,
                             payload,
                             props,
                             notify=True,
                             **kwds):
        # if the payload represents a new instance of `model`
        if action_type == get_crud_action('delete', name or Model):
            try:
                # the props of the message
                message_props = {}
                # if there was a correlation id in the request
                if 'correlation_id' in props:
                    # make sure it ends up in the reply
                    message_props['correlation_id'] = props['correlation_id']
                # the id in the payload representing the record to delete
                record_id = payload['id'] if 'id' in payload else payload['pk']
                # get the model matching the payload
                try:
                    model_query = Model.select().where(
                        Model.primary_key() == record_id)
                except KeyError:
                    raise RuntimeError(
                        "Could not find appropriate id to remove service record."
                    )
                # remove the model instance
                model_query.get().delete_instance()
                # if we need to tell someone about what happened
                if notify:
                    # publish the success event
                    await service.event_broker.send(
                        payload='{"status":"ok"}',
                        action_type=change_action_status(
                            action_type, success_status()),
                        **message_props)

            # if something goes wrong
            except Exception as err:
                # if we need to tell someone about what happened
                if notify:
                    # publish the error as an event
                    await service.event_broker.send(
                        payload=str(err),
                        action_type=change_action_status(
                            action_type, error_status()),
                        **message_props)
                # otherwise we aren't supposed to notify
                else:
                    # raise the exception normally
                    raise err
Пример #6
0
async def query_handler(service, action_type, payload, props, **kwds):
    """
        This action handler interprets the payload as a query to be executed
        by the api gateway service.
    """
    # check that the action type indicates a query
    if action_type == query_action_type():
        print('encountered query event {!r} '.format(payload))
        # perform the query
        result = await parse_string(payload,
                                    service.object_resolver,
                                    service.connection_resolver,
                                    service.mutation_resolver,
                                    obey_auth=False)

        # the props for the reply message
        reply_props = {
            'correlation_id': props['correlation_id']
        } if 'correlation_id' in props else {}

        # publish the success event
        await service.event_broker.send(payload=result,
                                        action_type=change_action_status(
                                            action_type, success_status()),
                                        **reply_props)
Пример #7
0
async def query_handler(service, action_type, payload, props, **kwds):
    """
        This action handler interprets the payload as a query to be executed
        by the api gateway service.
    """
    # check that the action type indicates a query
    if action_type == query_action_type():
        print('encountered query event {!r} '.format(payload))
        # perform the query
        result = await parse_string(payload,
            service.object_resolver,
            service.connection_resolver,
            service.mutation_resolver,
            obey_auth=False
        )

        # the props for the reply message
        reply_props = {'correlation_id': props['correlation_id']} if 'correlation_id' in props else {}

        # publish the success event
        await service.event_broker.send(
            payload=result,
            action_type=change_action_status(action_type, success_status()),
            **reply_props
        )
Пример #8
0
    def test_can_change_action_types(self):

        #  try to creat a crud action for a model
        action_type = get_crud_action(method='create', model=self.model)
        # try to change the action
        success_action = change_action_status(action_type, 'success')
        # make sure the new action type is in the result
        assert success_action == 'create.testModel.success', (
            "New action type did not have the correct form.")
Пример #9
0
    def test_can_change_action_types(self):

        #  try to creat a crud action for a model
        action_type = get_crud_action(method='create', model=self.model)
        # try to change the action
        success_action = change_action_status(action_type, 'success')
        # make sure the new action type is in the result
        assert success_action == 'create.testModel.success', (
            "New action type did not have the correct form."
        )
Пример #10
0
    async def action_handler(service, action_type, payload, props, notify=True, **kwds):
        # if the payload represents a new instance of `model`
        if action_type == get_crud_action('delete', name or Model):
            try:
                # the props of the message
                message_props = {}
                # if there was a correlation id in the request
                if 'correlation_id' in props:
                    # make sure it ends up in the reply
                    message_props['correlation_id'] = props['correlation_id']
                # the id in the payload representing the record to delete
                record_id = payload['id'] if 'id' in payload else payload['pk']
                # get the model matching the payload
                try:
                    model_query = Model.select().where(Model.primary_key() == record_id)
                except KeyError:
                    raise RuntimeError("Could not find appropriate id to remove service record.")
                # remove the model instance
                model_query.get().delete_instance()
                # if we need to tell someone about what happened
                if notify:
                    # publish the success event
                    await service.event_broker.send(
                        payload='{"status":"ok"}',
                        action_type=change_action_status(action_type, success_status()),
                        **message_props
                    )

            # if something goes wrong
            except Exception as err:
                # if we need to tell someone about what happened
                if notify:
                    # publish the error as an event
                    await service.event_broker.send(
                        payload=str(err),
                        action_type=change_action_status(action_type, error_status()),
                        **message_props
                    )
                # otherwise we aren't supposed to notify
                else:
                    # raise the exception normally
                    raise err
Пример #11
0
    async def action_handler(service,
                             action_type,
                             payload,
                             props,
                             notify=True,
                             **kwds):
        # if the payload represents a new instance of `Model`
        if action_type == get_crud_action('update', name or Model):
            try:
                # the props of the message
                message_props = {}
                # if there was a correlation id in the request
                if 'correlation_id' in props:
                    # make sure it ends up in the reply
                    message_props['correlation_id'] = props['correlation_id']

                # grab the nam eof the primary key for the model
                pk_field = Model.primary_key()

                # make sure there is a primary key to id the model
                if not pk_field.name in payload:
                    # yell loudly
                    raise ValueError(
                        "Must specify the pk of the model when updating")

                # grab the matching model
                model = Model.select().where(
                    pk_field == payload[pk_field.name]).get()

                # remove the key from the payload
                payload.pop(pk_field.name, None)

                # for every key,value pair
                for key, value in payload.items():
                    # TODO: add protection for certain fields from being
                    # changed by the api
                    setattr(model, key, value)

                # save the updates
                model.save()

                # if we need to tell someone about what happened
                if notify:
                    # publish the scucess event
                    await service.event_broker.send(
                        payload=ModelSerializer().serialize(model),
                        action_type=change_action_status(
                            action_type, success_status()),
                        **message_props)

            # if something goes wrong
            except Exception as err:
                # if we need to tell someone about what happened
                if notify:
                    # publish the error as an event
                    await service.event_broker.send(
                        payload=str(err),
                        action_type=change_action_status(
                            action_type, error_status()),
                        **message_props)
                # otherwise we aren't supposed to notify
                else:
                    # raise the exception normally
                    raise err