How to use the pynamodb.attributes.Attribute function in pynamodb

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

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

github pynamodb / PynamoDB / pynamodb / expressions / projection.py View on Github external
def _get_document_path(attribute):
    if isinstance(attribute, Attribute):
        return [attribute.attr_name]
    if isinstance(attribute, Path):
        return attribute.path
    return attribute.split('.')
github pynamodb / PynamoDB / pynamodb / attributes.py View on Github external
"""
    attr_type = STRING

    def serialize(self, value):
        """
        Returns a unicode string
        """
        if value is None or not len(value):
            return None
        elif isinstance(value, six.text_type):
            return value
        else:
            return six.u(value)


class JSONAttribute(Attribute):
    """
    A JSON Attribute

    Encodes JSON to unicode internally
    """
    attr_type = STRING

    def serialize(self, value):
        """
        Serializes JSON to unicode
        """
        if value is None:
            return None
        encoded = json.dumps(value)
        try:
            return unicode(encoded)
github pynamodb / PynamoDB / pynamodb / attributes.py View on Github external
"""
        Returns a base64 encoded binary string
        """
        return b64encode(value).decode(DEFAULT_ENCODING)

    def deserialize(self, value):
        """
        Returns a decoded string from base64
        """
        try:
            return b64decode(value.decode(DEFAULT_ENCODING))
        except AttributeError:
            return b64decode(value)


class BinarySetAttribute(SetMixin, Attribute):
    """
    A binary set
    """
    attr_type = BINARY_SET
    null = True

    def serialize(self, value):
        """
        Returns a base64 encoded binary string
        """
        if value and len(value):
            return [b64encode(val).decode(DEFAULT_ENCODING) for val in sorted(value)]
        else:
            return None

    def deserialize(self, value):
github yfilali / graphql-pynamodb / graphene_pynamodb / utils.py View on Github external
def get_key_name(model):
    if not issubclass(model, Model):
        raise TypeError("Invalid type passed to get_key_name: %s" % model.__class__)

    if model in MODEL_KEY_REGISTRY:
        return MODEL_KEY_REGISTRY[model]

    for attr in vars(model):
        attr = getattr(model, attr)
        if isinstance(attr, Attribute) and attr.is_hash_key:
            MODEL_KEY_REGISTRY[model] = attr.attr_name
            return attr.attr_name
github pynamodb / PynamoDB / pynamodb / attributes.py View on Github external
return int(val) if isinstance(val, float) else val

    def serialize(self, value):
        """
        Cast value to int then encode as JSON
        """
        return super(VersionAttribute, self).serialize(int(value))

    def deserialize(self, value):
        """
        Decode numbers from JSON and cast to int.
        """
        return int(super(VersionAttribute, self).deserialize(value))


class TTLAttribute(Attribute):
    """
    A time-to-live attribute that signifies when the item expires and can be automatically deleted.
    It can be assigned with a timezone-aware datetime value (for absolute expiry time)
    or a timedelta value (for expiry relative to the current time),
    but always reads as a UTC datetime value.
    """
    attr_type = NUMBER

    def _normalize(self, value):
        """
        Converts value to a UTC datetime
        """
        if value is None:
            return
        if isinstance(value, timedelta):
            value = int(time.time() + value.total_seconds())
github pynamodb / PynamoDB / pynamodb / attributes.py View on Github external
"""
        Takes a UTC datetime string and returns a datetime object
        """
        try:
            return _fast_parse_utc_datestring(value)
        except (ValueError, IndexError):
            try:
                # Attempt to parse the datetime with the datetime format used
                # by default when storing UTCDateTimeAttributes.  This is signifantly
                # faster than always going through dateutil.
                return datetime.strptime(value, DATETIME_FORMAT)
            except ValueError:
                return parse(value)


class NullAttribute(Attribute):
    attr_type = NULL

    def serialize(self, value):
        return True

    def deserialize(self, value):
        return None


class MapAttribute(Attribute, AttributeContainer):
    """
    A Map Attribute

    The MapAttribute class can be used to store a JSON document as "raw" name-value pairs, or
    it can be subclassed and the document fields represented as class attributes using Attribute instances.
github pynamodb / PynamoDB / pynamodb / attributes.py View on Github external
def __ne__(self, other):
        if self._is_attribute_container():
            return AttributeContainer.__ne__(self, other)
        return Attribute.__ne__(self, other)
github pynamodb / PynamoDB / pynamodb / attributes.py View on Github external
def __eq__(self, other):
        if self._is_attribute_container():
            return AttributeContainer.__eq__(self, other)
        return Attribute.__eq__(self, other)
github pynamodb / PynamoDB / pynamodb / attributes.py View on Github external
if value is None:
            return None
        encoded = json.dumps(value)
        try:
            return unicode(encoded)
        except NameError:
            return encoded

    def deserialize(self, value):
        """
        Deserializes JSON
        """
        return json.loads(value, strict=False)


class BooleanAttribute(Attribute):
    """
    A class for boolean attributes
    """
    attr_type = BOOLEAN

    def serialize(self, value):
        if value is None:
            return None
        elif value:
            return True
        else:
            return False

    def deserialize(self, value):
        return bool(value)
github pynamodb / PynamoDB / pynamodb / attributes.py View on Github external
return datetime.strptime(value, DATETIME_FORMAT)
            except ValueError:
                return parse(value)


class NullAttribute(Attribute):
    attr_type = NULL

    def serialize(self, value):
        return True

    def deserialize(self, value):
        return None


class MapAttribute(Attribute, AttributeContainer):
    """
    A Map Attribute

    The MapAttribute class can be used to store a JSON document as "raw" name-value pairs, or
    it can be subclassed and the document fields represented as class attributes using Attribute instances.

    To support the ability to subclass MapAttribute and use it as an AttributeContainer, instances of
    MapAttribute behave differently based both on where they are instantiated and on their type.
    Because of this complicated behavior, a bit of an introduction is warranted.

    Models that contain a MapAttribute define its properties using a class attribute on the model.
    For example, below we define "MyModel" which contains a MapAttribute "my_map":

    class MyModel(Model):
       my_map = MapAttribute(attr_name="dynamo_name", default={})