簡體   English   中英

具有多個數據庫的 PynamoDB 相同模型

[英]PynamoDB same model with multipe databases

PynamoDB 的實現方式是查看特定的單個 DynamoDB 表:

class UserModel(Model):
    class Meta:
        # Specific table.
        table_name = 'dynamodb-user'
        region = 'us-west-1'

我的基礎架構的工作方式是它擁有與我的客戶端一樣多的 dynamodb 表,因此單個 Lambda 函數必須處理任何數量的結構相同的單獨表,例如代表“UserModel”。 我無法指定一個具體的。

我如何使這個模型定義動態化?

謝謝!

可能的解決方案:

def create_user_model(table_name: str, region: str):
    return type("UserModel", (Model,), {
        "key" : UnicodeAttribute(hash_key=True),
        "range_key" : UnicodeAttribute(range_key=True),
        # Place for other keys
        "Meta": type("Meta", (object,), {
            "table_name": table_name,
            "region": region,
            "host": None,
            "billing_mode": 'PAY_PER_REQUEST',
        })
    })
UserModel_dev = create_user_model("user_model_dev", "us-west-1")
UserModel_prod = create_user_model("user_model_prod", "us-west-1")

更新:

更清潔的版本:

class UserModel(Model):
    key = UnicodeAttribute(hash_key=True)
    range_key = UnicodeAttribute(range_key=True)

    @staticmethod
    def create(table_name: str, region: str):
        return type("UserModelDynamic", (UserModel,), {
            "Meta": type("Meta", (object,), {
                "table_name": table_name,
                "region": region,
                "host": None,
                "billing_mode": 'PAY_PER_REQUEST',
            })
        })

開源一個經過測試和工作的解決方案。

https://github.com/Biomapas/B.DynamoDbCommon/blob/master/b_dynamodb_common/models/model_type_factory.py

閱讀 README.md 了解更多詳情。

代碼:

from typing import TypeVar, Generic, Type

from pynamodb.models import Model

T = TypeVar('T')


class ModelTypeFactory(Generic[T]):
    def __init__(self, model_type: Type[T]):
        self.__model_type = model_type

        # Ensure that given generic belongs to pynamodb.Model class.
        if not issubclass(model_type, Model):
            raise TypeError('Given model type must inherit from pynamodb.Model class!')

    def create(self, custom_table_name: str, custom_region: str) -> Type[T]:
        parent_class = self.__model_type

        class InnerModel(parent_class):
            class Meta:
                table_name = custom_table_name
                region = custom_region

        return InnerModel

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM