1

プロパティ タイプに基づいて基になる変換を実行するように、文字列からデータストア エンティティ インスタンスのプロパティを設定する一般的な方法はありますか。

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に比較的慣れていないため、ドキュメントから見つけることができませんでした).

あなたの助けに感謝。

4

1 に答える 1

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) ) 

アップデート:

のドキュメントはありません: db.class_for_kind(kind) しかし、より良い解決策があります。次の 2 行を置き換えます。

__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)
于 2012-12-31T16:02:20.570 に答える