Last active
May 14, 2024 15:55
-
-
Save medwig/8ff559c9343e3d9db0cb773caf774112 to your computer and use it in GitHub Desktop.
An enumerated type (enum) attribute for pynamodb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pynamodb.models import Model | |
from pynamodb.constants import STRING | |
from pynamodb.attributes import UnicodeAttribute | |
ENUM = ('FOO', 'BAR', 'BAZ') | |
class EnumUnicodeAttribute(UnicodeAttribute): | |
""" | |
An enumerated unicode attribute | |
""" | |
attr_type = STRING | |
def serialize(self, value): | |
""" Raises ValueError if input value not in ENUM, otherwise continues as parent class """ | |
if value not in ENUM: | |
raise ValueError(f"{self.attr_name} must be one of {ENUM}, not '{value}'") | |
else: | |
return UnicodeAttribute.serialize(self, value) | |
class Task(Model): | |
""" | |
A schema for an object in the Task table | |
""" | |
class Meta: | |
table_name = 'task-table' | |
status = EnumUnicodeAttribute() | |
mmoss82
commented
Jan 13, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment