什么时候应该在Google App Engine应用程序中使用Expando Class?

时间:2010-10-24 22:52:44

标签: google-app-engine expando

Google App Engine Expando Class有哪些应用程序? 与此相关的良好实践是什么?

1 个答案:

答案 0 :(得分:3)

Expandos的两个常见用途是部分修复的模式和deleting旧属性。

我经常使用Expando,因为我的实体需要稍微不同的属性;换句话说,当我需要一个“部分”动态架构时。一个用例是一个应用程序接受订单,其中一些产品是液体(想想水),一些是物理单位(想想DVD),一些是'其他'(想想面粉)。总是需要一些字段,如商品代码,价格和数量。但是,如果还需要计算数量的详细信息呢?

通常,固定模式解决方案是为我们可能使用的所有变量添加属性:权重,维度,股票权重之前和之后,等等。太糟糕了。对于每个实体,大多数其他领域都不需要。

class Order(db.Model):
    # These fields are always needed.
    item_code = db.StringProperty()
    unit_of_measure = db.StringProperty()
    unit_price = db.FloatProperty()
    quantity = db.FloatProperty()

    # These fields are used depending on the unit of measure.
    weight = db.FloatProperty()
    volume = db.FloatProperty()
    stock_start_weight = db.FloatProperty()
    stock_end_weight = db.FloatProperty()

借助Expando,我们可以做得更好。我们可以使用unit_of_measure告诉我们如何计算数量。计算数量的函数可以设置动态字段,读取该方法信息的函数知道要查找的内容。并且,该实体没有一堆不需要的属性。

class Order(db.Expando):
    # Every instance has these fields.
    item_code = db.StringProperty()
    unit_of_measure = db.StringProperty()
    unit_price = db.FloatProperty()
    quantity = db.FloatProperty()


def compute_gallons(entity, kilograms, kg_per_gallon):
    # Set the fixed fields.
    entity.unit_of_measure = 'GAL'
    entity.quantity = kilograms / kg_per_gallon

    # Set the gallon specific fields:
    entity.weight = kilograms
    entity.density = kg_per_gallon

通过使用text或blob属性并将“other”值的dict序列化,可以获得类似的结果。 Expando基本上为你“自动化”。