我正在嘗試使用最常用的沙發視圖(主要是用於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__
?
非常感謝您的幫助。