首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pynamodb基于已有类对象创建模型

pynamodb基于已有类对象创建模型
EN

Stack Overflow用户
提问于 2020-01-14 08:03:22
回答 1查看 342关注 0票数 0

我正在Python Flask项目中使用pynamodb,并开始构建我的模型来定义将用于表的对象。

文档说明您可以按如下方式定义模型:

代码语言:javascript
复制
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)

但是,我已经在另一个模块中定义了一个已存在的类,如下所示:

代码语言:javascript
复制
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表的模式匹配。

EN

回答 1

Stack Overflow用户

发布于 2020-05-27 13:43:01

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

代码语言:javascript
复制
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 Schema属性并分配相应的Pynamodb属性。希望它能帮上忙!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59725877

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档