record - adding zope Variable types programmatically
by
kedai
—
last modified
Apr. 29, 04 03:08 PM
In zope, we can actually determines the variable types returned by forms. This is somewhat not safe, but if all we have are trusted users, then it should not matter. Some of zope's core products, like ZCTextIndex, uses form variable types.
A custom product needed to add a Catalog with special indexes during instantiation. We want to use ZCTextIndex since it comes with weighted results.
Here's the code to add Catalog:
#postinit method to add extra stuff after object instantiation
def _postinit(self,REQUEST):
"""post init - add catalog."""
RESPONSE = REQUEST.RESPONSE
#create our Catalog
self.zc= ZCatalog.manage_addZCatalog(self,id='Catalog',title='',vocab_id='create_default_catalog_',REQUEST=None)
self.zc = getattr(self,'Catalog')
elements=REQUEST['elements']
ZCTextIndex.manage_addLexicon(self.zc, 'reslex','',
elements)
self.zc.manage_addColumn('msgbody')
The above code will add a Catalog with id 'Catalog' and a ZCLexicon with id 'reslex'. Now, to add other index, we can just do this:
self.manage_addIndex(index_name, index_type)
This will work with all indexes, like FieldIndex, TextIndex, etc; except for ZCTextIndex and DateRangeIndex. Or generally, all indexes that needed the *extra* keyword.
If we look at the ZMI add form, we can see that extra is a record, or maybe records. How? Check out the html source.
So, we must now instantiate a record type. Where is that done? All type checking are done in ZPublisher.HTTPRequest. So, we do:
from ZPublisher.HTTPRequest import record
and then, set our *extra* as necessary.
#set extra stuff to add ZCTextIndex. extra is a record() and we set attributes accordingly
#should be done only once, and used when we want to add ZCTextIndex
extra=record()
setattr(extra,'lexicon_id','reslex')
setattr(extra,'index_type','Cosine Measure')
#add indexes
self.zc.manage_addIndex('msgbody','ZCTextIndex',extra)
self.zc.manage_addIndex('date','FieldIndex')
We now are done.