pynamodb基于现有类对象创建模型

2024-06-16 18:24:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在PythonFlask项目中使用pynamodb,并开始构建我的模型来定义将与表一起使用的对象

文档中说您定义了一个模型,如下所示:

from pynamodb.models import Model
from pynamodb.attributes import UnicodeAttribute

    class UserModel(Model):
        """
        A DynamoDB User
        """
        class Meta:
            table_name = "dynamodb-user"
        email = UnicodeAttribute(null=True)
        first_name = UnicodeAttribute(range_key=True)
        last_name = UnicodeAttribute(hash_key=True)

但是,我已经在另一个模块中定义了一个现有类,请参见下文:

class ActivityTask:
    def __init__(self,task_name, sequence_order):
        self.taskid = uuid.uuid4()
        self.taskcreated = datetime.datetime.now()
        self.taskname = task_name
        self.sequenceorder = sequence_order

是否有一种方法可以让我以某种方式“移植”现有的ActivityTask类对象,以便将其用作模型?因为它已经与讨论中的DynamoDB表的模式匹配


Tags: 对象keynamefrom模型importselftrue
1条回答
网友
1楼 · 发布于 2024-06-16 18:24:00

下面是我创建的一个类,用于从Marshmellow类自动生成Pynamodb模型:

class PynamodbModel:
def __init__(self, base_object):
    self.base_object = base_object

    attributes = self.make_attributes(self.base_object.schema)

    meta_attr = {"table_name" : self.base_object.__name__}

    attributes['Meta'] = type("Meta", (), meta_attr)

    self.table : Model = type("Table", (Model,), attributes)

def convert_attr(self, attr):
    if type(attr) == Nested:
        atttr = attr.inner.nested

def make_attributes(self, schema_obj):
    attributes = {}

    for name, elem in schema_obj._declared_fields.items():
        if name == 'id':
            attributes[name] = attibute_conversion[type(elem)](hash_key=True)
        elif type(elem) == List:
            if type(elem.inner) == Nested:
                attributes[name] = attibute_conversion[type(elem)](of=self.make_nested_attr(elem.inner.nested))
            else:
                attributes[name] = attibute_conversion[type(elem)]()

        elif type(elem) == Nested:
            attributes[name] = self.make_nested_attr(elem.nested)

        else:
            attributes[name] = attibute_conversion[type(elem)]()

    return attributes

def make_nested_attr(self, nested_schema):

    attributes = self.make_attributes(nested_schema)

    return type(nested_schema.__class__.__name__, (MapAttribute,), attributes)

Go here to see the full example !

我基本上只是迭代Marshmellow模式属性并分配相应的Pynamodb属性。希望能有帮助

相关问题 更多 >