2012-12-31 18 views
1

是否有一種通用方法來從字符串中設置數據存儲區實體實例中的屬性,以便根據Property類型執行基礎轉換。Appengine Datastore Propery fromString()方法

person = Person() 
person.setattr("age", "26") # age is an IntegerProperty 
person.setattr("dob", "1-Jan-2012",[format]) # dob is a Date Property 

這很容易編寫,但這是一個非常常見的用例,並且想知道Datastore Python API是否有任何規定。

(對不起,如果這是一個行人問題,我對Appengine比較陌生,無法找到文檔)。

感謝您的幫助。

回答

2

我幾天前對另一個用例有同樣的問題。爲了解決這個問題,我創建了一個屬性類型列表,來完成我需要的轉換。此解決方案使用未記錄的db函數和db.Model類的內部函數。也許有更好的解決方案。

from google.appengine.ext import db 
kind = 'Person' 
models_module = { 'Person' : 'models'}  # module to import the model kind from 

model_data_types = {}      # create a dict of properties, like DateTimeProperty, IntegerProperty 
__import__(models_module[kind], globals(), locals(), [kind], -1) 
model_class = db.class_for_kind(kind)  # not documented 
for key in model_class._properties :   # the internals of the model_class object 
    model_data_types[key] = model_class._properties[key].__class__.__name__ 

要轉換的字符串,你可以創建一個像字符串轉換函數的類:

class StringConversions(object) 

    def IntegerProperty(self, astring): 

     return int(astring)  

    def DateTimeProperty(self, astring): 

     # do the conversion here 
     return .... 

而且使用它像:

property_name = 'age' 
astring = '26' 

setattr(Person, property_name, getattr(StringConversions, model_data_types[property_name])(astring)) 

UPDATE:

沒有文檔:db.class_for_kind(kind) 但有更好的解決辦法。更換這兩行:

__import__(models_module[kind], globals(), locals(), [kind], -1) 
model_class = db.class_for_kind(kind)  # not documented 

有了:

module = __import__(models_module[kind], globals(), locals(), [kind], -1) 
model_class = getattr(module, kind) 
+0

這是有趣/有用的功能,從名稱(db.class_for_kind)建立一個實體實例...我的問題是稍有不同(對不起,如果不是理解你的答案)。我很有興趣從字符串內部化屬性(屬性字段) - 就像我在我的問題中提到的那樣。我希望總是傳遞一個字符串並讓函數根據屬性類型轉換爲python基本類型(所以如果它是一個IntegerProperty,那麼它將執行一個int(strArg),然後在該propery中執行一個setattr() ..(謝謝) – user1055761

+0

生成的字典爲每個屬性名稱提供了一個Model屬性的數據類型。我的用例:在兩個GAE域之間交換模型(所有實體)和/或壓縮模型實體的函數。該函數用於轉換數據類型,如BlobReferenceProperty,BlobProperty和LinkProperty(帶有get_serving_url)。在您的用例中,您可以將字符串轉換爲屬性,其中轉換由結果模型(Person)中屬性的數據類型控制。 – voscausa

相關問題