I'd like to be able to automatically insert an entity with a reference t another entity directly from a message, using Google Endpoints.
我希望能夠使用Google端點直接從郵件中自動插入帶有引用另一個實體的實體。
To transmit ReferenceProperty
in message, I use the encoded string value of the Key
. That is fine for sending message, but when receiving message, and creating an entity of it, I cannot just pass the encoded string as a parameter to the constructor.
要在消息中傳輸ReferenceProperty,我使用Key的編碼字符串值。這對於發送消息很好,但是當接收消息並創建它的實體時,我不能只將編碼的字符串作為參數傳遞給構造函數。
For instance, say I have two classes that inherits from BaseModel
which itself inherits from db.models
例如,假設我有兩個繼承自BaseModel的類,它本身繼承自db.models
class TestModel2(models.BaseModel):
test_string = db.StringProperty(required=True)
class TestModel(models.BaseModel):
test2 = db.ReferenceProperty(TestModel2)
test2_id = property(models.BaseModel._get_attr_id_builder('test2'),
models.BaseModel._set_attr_id_builder('test2'))
And a message class
還有一個消息類
class TestModelMessage(messages.Message):
test2_id = messages.StringField(4)
I want to be able to create an Entity
TestModel
directly of the TestModelMessage
.
我希望能夠直接創建TestModelMessage的Entity TestModel。
I managed to do it in the other way (from to entity to message) using a property. But in the other way it doesn't work since I have the feeling that the constructor for db.models
will only set the attributes that inherits db.Property
. Thus the setter for the property won't be called...
我設法使用屬性以另一種方式(從實體到消息)執行此操作。但另一方面它不起作用,因為我覺得db.models的構造函數只會設置繼承db.Property的屬性。因此,不會調用屬性的setter ...
How could I do this?
我怎么能這樣做?
I thought of overriding the __init__
in BaseModel
but then when calling the __init__
of db.models
it will probably override the ReferenceProperty
.
我想過覆蓋BaseModel中的__init__,但是當調用db.models的__init__時,它可能會覆蓋ReferenceProperty。
0
So, I added a _ref_properties
field to the BaseModel
class. For the previous example, it would be _ref_properties = {'test2': 'test2_id'}
所以,我在BaseModel類中添加了一個_ref_properties字段。對於前面的示例,它將是_ref_properties = {'test2':'test2_id'}
Then I added this class method
然后我添加了這個類方法
@classmethod
def from_message(cls, message, *args):
attributes = {attr: getattr(message, attr) for attr in args}
for attribute, property in cls._ref_properties.items():
attributes[attribute] = db.Key(encoded=getattr(message, property))
entity = cls(**attributes)
return entity
And it seems to work. Probably not the best. Any remarks or better solution?
它似乎工作。可能不是最好的。任何言論或更好的解決方案?
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/05/11/72500f5b4c5a468074c1f0b9c7e3f3bf.html。