2013-06-29 27 views
1

我正在嘗試使用最常用的沙發視圖(主要是用於CRUD)構建基礎模型類。python-couchdb在實例化後將ViewField添加到Model中

我不能只是將ViewFields添加到基類中,因爲每個模型類名稱中的js字符串都必須稍作更改。
這在基類__init__內部沒有問題,但由於某些原因,ViewField無法工作。

當使用一個視場一般像這樣:

class MyModel(Document): 
    only_carrots = ViewField("mymodel", js-string) 

那麼,如果我們運行:

mod = MyModel() 
mod.only_carrots 

它會顯示:
<ViewDefinition '_design/mymodel/_view/only_carrots'>

但如果視場是在加入__init__,看起來像這樣:

<flaskext.couchdb.ViewField object at 0x10fe8f190> 

在基本模型中運行的代碼是這樣的:

for attr_name in dir(self): 
     if not attr_name.startswith("_") and attr_name not in ["id", "rev"]: 
      attr_val = getattr(self, attr_name) 
      if isinstance(attr_val, CouchView): 
       vd = ViewField(self.doc_type, attr_val.template.render(self.__dict__), name=attr_name, wrapper=self.__class__) 
       setattr(self, attr_name, vd) 

的CouchView類是我自己的。它僅用於存儲ViewField的信息,使其不會被元類內的代碼檢測到。

Document類(其基本模型是子類)有__metaclass__。這至少需要處理一部分工作來獲得ViewField的工作,但我認爲我已經在自己的課程中介紹了該部分。

爲Python-CouchDB的源在這裏找到:
https://code.google.com/p/couchdb-python/source/browse/#hg%2Fcouchdb

而對於燒瓶CouchDB的:
https://bitbucket.org/leafstorm/flask-couchdb/src

那麼,如何使視場工作時,它是由__init__,因此加不可用於元類中的__new__

非常感謝您的幫助。

回答

0

嗯,我想我明白了。或者至少,一個解決方法。

所有ViewField所做的就是啓動ViewDefinition並使用wrapper -param填充它所綁定的類。

所以,做這一切在初始化時,只需撥打ViewDefinition代替,就像這樣:

def __init__(self, *args, **kwargs): 
    if not self.doc_type: 
     self.doc_type = self.__class__.__name__ 
    for attr_name in dir(self): 
     if not attr_name.startswith("_") and attr_name not in ["id", "rev"]: 
      attr_val = getattr(self, attr_name) 
      if isinstance(attr_val, CouchView): 
       setattr(self, attr_name, ViewDefinition(self.doc_type, attr_name, attr_val.template.render(self.__dict__), wrapper=self)) 

當然,現在你必須記住它們添加到管理員之前,實例化模型類(說到與瓶擴展):

user = User() 
manager.add_document(user) 

這在測試時咬我。當我疲倦的時候,要停止這樣做。
由於某些原因,您需要將_data = {}添加到您的自定義基類中。我無法弄清楚爲什麼它沒有正確設置,但它是一個簡單的修復。

相關問題