我正在Python Flask项目中使用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表的模式匹配。
发布于 2020-05-27 05:43:01
下面是我创建的一个类,用于从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 Schema属性并分配相应的Pynamodb属性。希望它能帮上忙!
https://stackoverflow.com/questions/59725877
复制相似问题