""" herd.py -- grok-based web application for managing mammoths """ import grok from zope import schema, interface, component from zope.app.intid import IntIds from zope.app.intid.interfaces import IIntIds from zope.app.catalog.catalog import Catalog from zope.app.catalog.interfaces import ICatalog from zope.app.catalog.field import FieldIndex def setup_catalog(catalog): catalog['name'] = FieldIndex('name', IMammoth) # only index mammoths class Herd(grok.Application, grok.Container): """Root application object and container for Mammoth objects. Also sets up a catalog with a field index for indexing mammoths.""" grok.local_utility(IntIds, provides=IIntIds) # necessary for catalog grok.local_utility(Catalog, provides=ICatalog, setup=setup_catalog) class HerdIndex(grok.View): """Default view for herd objects. It lets you search for mammoths inside the herd and add new mammoths. Actual HTML rendering by herd_templates/herdindex.pt (which is automatically found according to the name of this Python module and the name of this view class)""" grok.context(Herd) # indicates which model the view is for grok.name('index') # URL name of the view def update(self): """This method is executed before the template is rendered. It allows us to perform operations such as processing request parameters or precomputing stuff that the template may need.""" query = self.request.form.get('query') if not query: return catalog = component.getUtility(ICatalog) self.search_results = catalog.searchResults(name=(query, query)) class IMammoth(interface.Interface): """Data schema for mammoths""" name = schema.TextLine( title=u'Name', description=u'Name of the Mammoth', ) class Mammoth(grok.Model): grok.implements(IMammoth) def __init__(self, name): self.name = name # this attribute will be indexed by the FieldIndex class AddMammoth(grok.AddForm): """Form that creates a new mammoth.""" grok.context(Herd) form_fields = grok.Fields(id=schema.TextLine(title=u"URL name")) form_fields += grok.AutoFields(IMammoth) # deduce form fields from schema @grok.action('Add mammoth') def add(self, id, name): self.context[id] = Mammoth(name) self.redirect(self.url(self.context))