Example #1
0
class DynamicMapDiscriminatorTestModel(Model, discriminator='Parent'):
    class Meta:
        host = 'http://localhost:8000'
        table_name = 'test'
    hash_key = UnicodeAttribute(hash_key=True)
    value = DynamicSubclassedMapAttribute(default=dict)
    type = DiscriminatorAttribute()
Example #2
0
class Base(Model):
    class Meta:
        table_name = "appstore"
        region = "us-west-2"
        billing_mode = "PAY_PER_REQUEST"

    pk = CompoundTemplateAttribute(
        hash_key=True,
        template="$type_#$ulid",
        attrs=["type_", "ulid"],
    )
    ulid = ULIDAttribute()
    cls = DiscriminatorAttribute(attr_name="__type")
    ttl = TTLAttribute(null=True)
    gsi1 = GSI1()
    gsi2 = GSI2()

    @property
    def type_(self):
        return self.__class__.__name__.upper()

    @property
    def created_at(self) -> datetime:
        """Based on a ULID `pk`, extract an aware datetime"""
        if ts := getattr(self.pk, "timestamp", None):
            return ts().datetime
        if ts := getattr(self.ulid, "timestamp", None):
            return ts().datetime
Example #3
0
class DiscriminatorTestModel(Model, discriminator='Parent'):
    class Meta:
        host = 'http://localhost:8000'
        table_name = 'test'
    hash_key = UnicodeAttribute(hash_key=True)
    value = TypedValue()
    values = ListAttribute(of=TypedValue)
    type = DiscriminatorAttribute()
Example #4
0
class Office(Model):
    class Meta:
        table_name = "OfficeModel"
        host = "http://localhost:{}".format(environ.get("DOCKER_PORT", 8000))
        aws_access_key_id = "my_access_key_id"
        aws_secret_access_key = "my_secret_access_key"

    office_id = UUIDAttribute(hash_key=True)
    address = Location()
    employees = ListAttribute(of=OfficeEmployeeMap)
    departments = UnicodeSetAttribute()
    numbers = NumberSetAttribute()
    security_number = UnicodeAttribute(null=True)
    office_times = ListAttribute()
    cls = DiscriminatorAttribute()
class OfficeSchema(ModelSchema):
    """Office Schema for PynamoDB Office Model.

    We are overriding PynamoDB
    NumberSetAttribute and UnicodeSetAttribute fields
    to maintain list order

    """

    numbers = fields.List(fields.Integer)
    departments = fields.List(fields.String)
    security_number = fields.Str(allow_none=True)
    cls = DiscriminatorAttribute()

    class Meta:
        """Schema Model Meta Class."""

        model = Office
        host = "http://localhost:{}".format(environ.get("DOCKER_PORT", 8000))
        aws_access_key_id = "my_access_key_id"
        aws_secret_access_key = "my_secret_access_key"
Example #6
0
class Base(Model):
    """Base relational class.

    Use this class to add functionality
    to PynamoDB Base class.
    """

    created_at = UTCDateTimeAttribute(default=get_time_now)
    updated_at = UTCDateTimeAttribute(default=get_time_now)
    cls = DiscriminatorAttribute()

    def __eq__(self, other):
        return self.uuid == other.uuid  # type: ignore

    @classmethod
    def table_exists(cls) -> None:
        """Check if Table exists.

        Running only in Development.
        :return: None
        """
        environment = os.getenv("ENVIRONMENT", "develop")
        logger.debug(
            f"Check if table {cls.Meta.table_name} on '{environment}' exists..."
        )
        if environment == "develop":
            if not cls.exists():
                logger.warning(
                    f"Table {cls.Meta.table_name} in {environment} "  # type: ignore
                    f"does not exist. Creating...")
                cls.create_table(wait=True)

    def save(self, **kwargs):
        """Validate before save DynamoDB."""
        self.table_exists()
        if self.validate():  # type: ignore
            self.updated_at = arrow.utcnow().datetime
            return super().save(**kwargs)

    def validate(self) -> bool:
        """Validate Enterprise Rules.

        This is a simple example. This
        method must run all model validations

        :return: Boolean
        """
        return True

    def __str__(self):
        return (
            f"<{{cookiecutter.model_name_camel}}Document("
            f"uuid={getattr(self, 'uuid')}, "
            f"created_at={self.created_at.isoformat() if self.created_at else '-'}, "
            f"id={id(self)})>")

    class Meta:
        table_name = get_table_name()
        host = get_nosql_database_url()
        read_capacity_units = settings["project.capacity.read"]
        write_capacity_units = settings["project.capacity.write"]
        connection = connection
Example #7
0
class TypedValue(MapAttribute):
    _cls = DiscriminatorAttribute(attr_name = 'cls')
    name = UnicodeAttribute()
Example #8
0
 class TestAttribute(MapAttribute, discriminator='new_value'):
     cls = DiscriminatorAttribute()
class MyDocument(BaseDocument, discriminator="my_document"):
    status = UnicodeEnumAttribute(MyStatus, default=MyStatus.CREATED)
    content = UnicodeAttribute()
    tokens = BinarySetAttribute()
    version = VersionAttribute(null=True)
    cls = DiscriminatorAttribute()
class BaseDocument(Model):
    uuid = UUIDAttribute(default=uuid.uuid4)
    description = UnicodeAttribute(default="bar")
    cls = DiscriminatorAttribute()
Example #11
0
 class DiscriminatedModel(Model):
     hash_key = UnicodeAttribute(hash_key=True)
     _cls = DiscriminatorAttribute()