def save_attributes(self, request_envelope, attributes):
        # type: (RequestEnvelope, Dict[str, object]) -> None
        """Saves attributes to the s3 bucket.

        :param request_envelope: Request Envelope passed during skill
            invocation
        :type request_envelope: ask_sdk_model.request_envelope.RequestEnvelope
        :param attributes: attributes to store in s3
        :type attributes: Dict[str, object]
        :rtype: None
        :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
        """
        obj_id = self.__get_object_id(request_envelope)
        json_data = json.dumps(attributes)
        try:
            self.s3_client.put_object(Body=json_data,
                                      Bucket=self.bucket_name,
                                      Key=obj_id)
        except ResourceNotExistsError:
            raise PersistenceException(
                "Failed to save attributes to s3 bucket {}."
                "Resource does not exist".format(self.bucket_name))
        except Exception as e:
            raise PersistenceException(
                "Failed to save attributes to s3 bucket. "
                "Exception of type {} occurred: {}".format(
                    type(e).__name__, str(e)))
Ejemplo n.º 2
0
    def save_attributes(self, request_envelope, attributes):
        # type: (RequestEnvelope, Dict[str, object]) -> None
        """Saves attributes to table in Dynamodb resource.

        Saves the attributes into Dynamodb table. Raises
        PersistenceException if table doesn't exist or ``put_item`` fails
        on the table.

        :param request_envelope: Request Envelope passed during skill
            invocation
        :type request_envelope: ask_sdk_model.RequestEnvelope
        :param attributes: Attributes stored under the partition keygen
            mapping in the table
        :type attributes: Dict[str, object]
        :rtype: None
        :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
        """
        try:
            table = self.dynamodb.Table(self.table_name)
            partition_key_val = self.partition_keygen(request_envelope)
            table.put_item(
                Item={
                    self.partition_key_name: partition_key_val,
                    self.attribute_name: attributes
                })
        except ResourceNotExistsError:
            raise PersistenceException(
                "DynamoDb table {} doesn't exist. Failed to save attributes "
                "to DynamoDb table.".format(self.table_name))
        except Exception as e:
            raise PersistenceException(
                "Failed to save attributes to DynamoDb table. Exception of "
                "type {} occurred: {}".format(type(e).__name__, str(e)))
Ejemplo n.º 3
0
    def delete_attributes(self, request_envelope):
        # type: (RequestEnvelope) -> None
        """Deletes attributes from table in Dynamodb resource.

        Deletes the attributes from Dynamodb table. Raises
        PersistenceException if table doesn't exist or ``delete_item`` fails
        on the table.

        :param request_envelope: Request Envelope passed during skill
            invocation
        :type request_envelope: ask_sdk_model.RequestEnvelope
        :rtype: None
        :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
        """
        try:
            table = self.dynamodb.Table(self.table_name)
            partition_key_val = self.partition_keygen(request_envelope)
            table.delete_item(Key={self.partition_key_name: partition_key_val})
        except ResourceNotExistsError:
            raise PersistenceException(
                "DynamoDb table {} doesn't exist. Failed to delete attributes "
                "from DynamoDb table.".format(self.table_name))
        except Exception as e:
            raise PersistenceException(
                "Failed to delete attributes in DynamoDb table. Exception of "
                "type {} occurred: {}".format(type(e).__name__, str(e)))
Ejemplo n.º 4
0
    def __create_table_if_not_exists(self):
        # type: () -> None
        """Creates table in Dynamodb resource if it doesn't exist and
        create_table is set as True.

        :rtype: None
        :raises: PersistenceException: When `create_table` fails on
            dynamodb resource.
        """
        if self.create_table:
            try:
                self.dynamodb.create_table(TableName=self.table_name,
                                           KeySchema=[{
                                               'AttributeName':
                                               self.partition_key_name,
                                               'KeyType': 'HASH'
                                           }],
                                           AttributeDefinitions=[{
                                               'AttributeName':
                                               self.partition_key_name,
                                               'AttributeType':
                                               'S'
                                           }],
                                           ProvisionedThroughput={
                                               'ReadCapacityUnits': 5,
                                               'WriteCapacityUnits': 5
                                           })
            except Exception as e:
                if e.__class__.__name__ != "ResourceInUseException":
                    raise PersistenceException(
                        "Create table if not exists request "
                        "failed: Exception of type {} "
                        "occurred: {}".format(type(e).__name__, str(e)))
Ejemplo n.º 5
0
def person_id_partition_keygen(request_envelope):
    # type: (RequestEnvelope) -> str
    """Retrieve person id from request envelope, to use as object key.

    This method retrieves the `person id` specific to a voice profile from
    the request envelope if it exists, to be used as an object key. If it
    doesn't exist, then the `user id` is returned instead.

    :param request_envelope: Request Envelope passed during skill
        invocation
    :type request_envelope: ask_sdk_model.RequestEnvelope
    :return: person Id retrieved from request envelope if exists, else
        fall back on User Id
    :rtype: str
    :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
    """
    try:
        person_id = request_envelope.context.system.person.person_id
    except AttributeError:
        try:
            person_id = user_id_partition_keygen(
                request_envelope=request_envelope)
        except PersistenceException:
            raise PersistenceException(
                "Couldn't retrieve person id or user id from request envelope, "
                "for partition key use")
    return person_id
def request_id_partition_keygen(request_envelope):
    """ Retrieve request id from request envelope, to use as partition key. """
    try:
        request_id = request_envelope.request.request_id
        return request_id
    except AttributeError:
        raise PersistenceException("Couldn't retrieve request id from "
                                   "request envelope, for partition key use")
    def delete_attributes(self, request_envelope):
        # type: (RequestEnvelope) -> None
        """Deletes attributes from s3 bucket.

        :param request_envelope: Request Envelope passed during skill
            invocation
        :type request_envelope: ask_sdk_model.request_envelope.RequestEnvelope
        :rtype: None
        :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
        """
        obj_id = self.__get_object_id(request_envelope)
        try:
            self.s3_client.delete_object(Bucket=self.bucket_name, Key=obj_id)
        except ResourceNotExistsError:
            raise PersistenceException(
                "Failed to delete attributes from s3 bucket {}."
                "Resource does not exist".format(self.bucket_name))
        except Exception as e:
            raise PersistenceException(
                "Failed to delete attributes from s3 bucket. "
                "Exception of type {} occurred: {}".format(
                    type(e).__name__, str(e)))
Ejemplo n.º 8
0
    def get_attributes(self, request_envelope):
        # type: (RequestEnvelope) -> Dict[str, object]
        """Get attributes from table in Dynamodb resource.

        Retrieves the attributes from Dynamodb table. If the table
        doesn't exist, returns an empty dict if the
        ``create_table`` variable is set as True, else it raises
        PersistenceException. Raises PersistenceException if `get_item`
        fails on the table.

        :param request_envelope: Request Envelope passed during skill
            invocation
        :type request_envelope: ask_sdk_model.RequestEnvelope
        :return: Attributes stored under the partition keygen mapping
            in the table
        :rtype: Dict[str, object]
        :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
        """
        try:
            table = self.dynamodb.Table(self.table_name)
            partition_key_val = self.partition_keygen(request_envelope)
            response = table.get_item(
                Key={self.partition_key_name: partition_key_val},
                ConsistentRead=True)
            if "Item" in response:
                return response["Item"][self.attribute_name]
            else:
                return {}
        except ResourceNotExistsError:
            raise PersistenceException(
                "DynamoDb table {} doesn't exist or in the process of "
                "being created. Failed to get attributes from "
                "DynamoDb table.".format(self.table_name))
        except Exception as e:
            raise PersistenceException(
                "Failed to retrieve attributes from DynamoDb table. "
                "Exception of type {} occurred: {}".format(
                    type(e).__name__, str(e)))
    def get_attributes(self, request_envelope):
        # type: (RequestEnvelope) -> Dict[str, object]
        """Retrieves the attributes from s3 bucket.

        :param request_envelope: Request Envelope passed during skill
            invocation
        :type request_envelope: ask_sdk_model.request_envelope.RequestEnvelope
        :return: attributes in the s3 bucket
        :rtype: Dict[str, object]
        :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
        """
        obj_id = self.__get_object_id(request_envelope)
        try:
            obj = self.s3_client.get_object(Bucket=self.bucket_name,
                                            Key=obj_id)
        except ResourceNotExistsError:
            raise PersistenceException(
                "Failed to get attributes from s3 bucket {}."
                "Resource does not exist".format(self.bucket_name))
        except ClientError as ex:
            if ex.response['Error']['Code'] == 'NoSuchKey':
                return {}
            raise PersistenceException(
                "Failed to get attributes from s3 bucket. "
                "Exception of type {} occurred: {}".format(
                    type(ex).__name__, str(ex)))
        try:
            body = obj.get(self.S3_OBJECT_BODY_NAME)
            if not body:
                return {}
            attributes = json.loads(body.read())
            return attributes
        except Exception as e:
            raise PersistenceException(
                "Failed to get attributes from s3 bucket. "
                "Exception of type {} occurred: {}".format(
                    type(e).__name__, str(e)))
def device_id_keygen(request_envelope):
    # type: (RequestEnvelope) -> str
    """Retrieve device id from request envelope.

    :param request_envelope: Request Envelope passed during skill
        invocation
    :type request_envelope: ask_sdk_model.RequestEnvelope
    :return: Device Id retrieved from request envelope
    :rtype: str
    :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
    """
    try:
        return request_envelope.context.system.device.device_id
    except AttributeError:
        raise PersistenceException(
            "Couldn't retrieve device id from request envelope")
Ejemplo n.º 11
0
def user_id_partition_keygen(request_envelope):
    # type: (RequestEnvelope) -> str
    """Retrieve user id from request envelope, to use as partition key.

    :param request_envelope: Request Envelope passed during skill
        invocation
    :type request_envelope: ask_sdk_model.RequestEnvelope
    :return: User Id retrieved from request envelope
    :rtype: str
    :raises: :py:class:`ask_sdk_core.exceptions.PersistenceException`
    """
    try:
        user_id = request_envelope.context.system.user.user_id
        return user_id
    except AttributeError:
        raise PersistenceException("Couldn't retrieve user id from request "
                                   "envelope, for partition key use")
Ejemplo n.º 12
0
def device_id_partition_keygen(request_envelope):
    # type: (RequestEnvelope) -> str
    """Retrieve device id from request envelope, to use as partition key.

    :param request_envelope: Request Envelope passed during skill
        invocation
    :type request_envelope: RequestEnvelope
    :return: Device Id retrieved from request envelope
    :rtype str
    :raises PersistenceException
    """
    try:
        device_id = request_envelope.context.system.device.device_id
        return device_id
    except AttributeError:
        raise PersistenceException("Couldn't retrieve device id from "
                                   "request envelope, for partition key use")