2016-07-20 11 views
1

に追加すると、計算されたフィールドを、フラスコなどのbefore_outputイベントで計算された値で埋めることができるスキーマに持ち込むことができますか?計算されたフィールドをeveスキーマ

schema = { 
    # Schema definition, based on Cerberus grammar. Check the Cerberus project 
    # (https://github.com/nicolaiarocci/cerberus) for details. 
    'firstname': { 
     'type': 'string', 
     'minlength': 1, 
     'maxlength': 10, 
    }, 
    'lastname': { 
     'type': 'string', 
     'minlength': 1, 
     'maxlength': 15, 
     'required': True, 
     # talk about hard constraints! For the purpose of the demo 
     # 'lastname' is an API entry-point, so we need it to be unique. 
     'unique': True, 
    }, 
    # 'role' is a list, and can only contain values from 'allowed'. 
    'role': { 
     'type': 'list', 
     'allowed': ["author", "contributor", "copy"], 
    }, 
    # An embedded 'strongly-typed' dictionary. 
    'location': { 
     'type': 'dict', 
     'schema': { 
      'address': {'type': 'string'}, 
      'city': {'type': 'string'} 
     }, 
    }, 
    'born': { 
     'type': 'datetime', 
    }, 
    'calculated_field': { 
     'type': 'string', 
    } 
} 

となり、calculated_fieldは独自のmongodbクエリ文を使用して埋められます。

+0

の前に挿入し、[イベントフック](http://python-eve.org/features.html#event-hooks)が解決しませんあなたの問題?挿入する前にcalculated_fieldの値を入力し、スキーマ内でread_onlyを手動で挿入しないようにすることもできます。 – gcw

答えて

2
  1. フィールドが読み取り専用としてフラグが設定されるように設定を更新してください:'calculated_field': {'readonly': True}。これにより、クライアントが誤ってフィールドに書き込むことを防ぐことができます。おそらくこれは文字列型として設定する必要はありません。
  2. 起動スクリプトにコールバック関数を追加します。これにより、アウトバウンド文書が処理され、計算された値が読み取り専用フィールドに追加されます。
  3. コールバックをアプリケーションのon_fetchedイベントにアタッチします。
  4. アプリケーションを起動します。

だからあなたのスクリプトは次のようになります。

from eve import Eve 

# the callback function 
def add_calculated_field_value(resource, response):           
    for doc in response['_items']:              
     doc['calculated_field'] = 'hello I am a calculated field' 

# instantiate the app and attach the callback function to the right event 
app = Eve() 
app.on_fetched_resource += add_calculated_field_value 

if __name__ == '__main__': 
    app.run() 
+0

この例ではありがとうございます:-) –

関連する問題