[Checkins] SVN: grok/branches/grokcore.xxx/ some files that were not added in previous commit; move grok/templatereg.py to grokcore/view/templatereg.py

Godefroid Chapelle gotcha at bubblenet.be
Thu Jul 17 10:19:52 EDT 2008


Log message for revision 88444:
  some files that were not added in previous commit; move grok/templatereg.py to grokcore/view/templatereg.py

Changed:
  U   grok/branches/grokcore.xxx/buildout.cfg
  A   grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/components.py
  A   grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/interfaces.py
  A   grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/meta.zcml
  A   grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/templatereg.py
  A   grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/util.py
  U   grok/branches/grokcore.xxx/src/grok/configure.zcml
  U   grok/branches/grokcore.xxx/src/grok/meta.py
  U   grok/branches/grokcore.xxx/src/grok/meta.zcml
  D   grok/branches/grokcore.xxx/src/grok/templatereg.py
  U   grok/branches/grokcore.xxx/src/grok/testing.py
  U   grok/branches/grokcore.xxx/src/grok/tests/zcml/directivepackage.py

-=-
Modified: grok/branches/grokcore.xxx/buildout.cfg
===================================================================
--- grok/branches/grokcore.xxx/buildout.cfg	2008-07-17 14:18:17 UTC (rev 88443)
+++ grok/branches/grokcore.xxx/buildout.cfg	2008-07-17 14:19:52 UTC (rev 88444)
@@ -65,6 +65,7 @@
 recipe = zc.recipe.testrunner
 eggs = grok 
        grokcore.view
+       ipdb
 defaults = ['--tests-pattern', '^f?tests$', '-v']
 
 [bundlemaker]

Added: grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/components.py
===================================================================
--- grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/components.py	                        (rev 0)
+++ grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/components.py	2008-07-17 14:19:52 UTC (rev 88444)
@@ -0,0 +1,77 @@
+from zope import component
+from zope import interface
+
+from zope.publisher.publish import mapply
+
+from grokcore.view import util
+
+
+class ViewMixin(object):
+
+    def _initialize(self):
+        self.__name__ = self.__view_name__
+        self.static = component.queryAdapter(
+            self.request,
+            interface.Interface,
+            name=self.module_info.package_dotted_name)
+
+    def _update_and_render(self):
+        mapply(self.update, (), self.request)
+        if self.request.response.getStatus() in (302, 303):
+            # A redirect was triggered somewhere in update().  Don't
+            # continue rendering the template or doing anything else.
+            return
+
+        template = getattr(self, 'template', None)
+        if template is not None:
+            return self._render_template()
+        return mapply(self.render, (), self.request)
+
+    def _render_template(self):
+        return self.template.render(self)
+
+    @property
+    def response(self):
+        return self.request.response
+
+    def url(self, obj=None, name=None, data=None):
+        """Return string for the URL based on the obj and name. The data
+        argument is used to form a CGI query string.
+        """
+        if isinstance(obj, basestring):
+            if name is not None:
+                raise TypeError(
+                    'url() takes either obj argument, obj, string arguments, '
+                    'or string argument')
+            name = obj
+            obj = None
+
+        if name is None and obj is None:
+            # create URL to view itself
+            obj = self
+        elif name is not None and obj is None:
+            # create URL to view on context
+            obj = self.context
+
+        if data is None:
+            data = {}
+        else:
+            if not isinstance(data, dict):
+                raise TypeError('url() data argument must be a dict.')
+
+        return util.url(self.request, obj, name, data=data)
+
+    def redirect(self, url):
+        return self.request.response.redirect(url)
+
+    def update(self):
+        pass
+
+    def namespace(self):
+        return {}
+
+    def default_namespace(self):
+        raise NotImplementedError
+
+    def application_url(self, name=None):
+        raise NotImplementedError

Added: grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/interfaces.py
===================================================================
--- grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/interfaces.py	                        (rev 0)
+++ grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/interfaces.py	2008-07-17 14:19:52 UTC (rev 88444)
@@ -0,0 +1,80 @@
+from zope import interface
+
+from zope.publisher.interfaces.browser import IBrowserPage, IBrowserView
+
+
+class IGrokView(IBrowserPage, IBrowserView):
+    """Grok views all provide this interface."""
+
+    context = interface.Attribute('context', "Object that the view presents.")
+
+    request = interface.Attribute('request', "Request that the view was looked"
+                                  "up with.")
+
+    response = interface.Attribute('response', "Response object that is "
+                                   "associated with the current request.")
+
+    static = interface.Attribute('static', "Directory resource containing "
+                                 "the static files of the view's package.")
+
+    def redirect(url):
+        """Redirect to given URL"""
+
+    def url(obj=None, name=None, data=None):
+        """Construct URL.
+
+        If no arguments given, construct URL to view itself.
+
+        If only obj argument is given, construct URL to obj.
+
+        If only name is given as the first argument, construct URL
+        to context/name.
+
+        If both object and name arguments are supplied, construct
+        URL to obj/name.
+
+        Optionally pass a 'data' keyword argument which gets added to the URL
+        as a cgi query string.
+        """
+
+    def default_namespace():
+        """Returns a dictionary of namespaces that the template
+        implementation expects to always be available.
+
+        This method is *not* intended to be overridden by application
+        developers.
+        """
+
+    def namespace():
+        """Returns a dictionary that is injected in the template
+        namespace in addition to the default namespace.
+
+        This method *is* intended to be overridden by the application
+        developer.
+        """
+
+    def update(**kw):
+        """This method is meant to be implemented by grok.View
+        subclasses.  It will be called *before* the view's associated
+        template is rendered and can be used to pre-compute values
+        for the template.
+
+        update() can take arbitrary keyword parameters which will be
+        filled in from the request (in that case they *must* be
+        present in the request)."""
+
+    def render(**kw):
+        """A view can either be rendered by an associated template, or
+        it can implement this method to render itself from Python.
+        This is useful if the view's output isn't XML/HTML but
+        something computed in Python (plain text, PDF, etc.)
+
+        render() can take arbitrary keyword parameters which will be
+        filled in from the request (in that case they *must* be
+        present in the request)."""
+
+    def application_url(name=None):
+        """Return the URL of the closest application object in the
+        hierarchy or the URL of a named object (``name`` parameter)
+        relative to the closest application object.
+        """

Added: grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/meta.zcml
===================================================================
--- grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/meta.zcml	                        (rev 0)
+++ grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/meta.zcml	2008-07-17 14:19:52 UTC (rev 88444)
@@ -0,0 +1,10 @@
+<configure
+    xmlns="http://namespaces.zope.org/zope"
+    xmlns:browser="http://namespaces.zope.org/browser"
+    xmlns:grok="http://namespaces.zope.org/grok">
+
+  <!-- ZPT support -->
+  <grok:grok package=".templatereg" />
+
+</configure>
+

Copied: grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/templatereg.py (from rev 88427, grok/branches/grokcore.xxx/src/grok/templatereg.py)
===================================================================
--- grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/templatereg.py	                        (rev 0)
+++ grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/templatereg.py	2008-07-17 14:19:52 UTC (rev 88444)
@@ -0,0 +1,131 @@
+from martian.error import GrokError
+from martian import util
+
+import os
+import zope.component
+import grok
+import warnings
+
+class TemplateRegistry(object):
+
+    def __init__(self):
+        self._reg = {}
+
+    def register(self, name, template):
+        self._reg[name] = dict(template=template, associated=False)
+
+    def markAssociated(self, name):
+        self._reg[name]['associated'] = True
+
+    def get(self, name):
+        entry = self._reg.get(name)
+        if entry is None:
+            return None
+        return entry['template']
+
+    def findFilesystem(self, module_info):
+        template_dir_name = grok.templatedir.bind().get(
+            module=module_info.getModule())
+        if template_dir_name is None:
+            template_dir_name = module_info.name + '_templates'
+
+        template_dir = module_info.getResourcePath(template_dir_name)
+
+        if not os.path.isdir(template_dir):
+            return
+
+        if module_info.isPackage():
+            return
+
+        for template_file in os.listdir(template_dir):
+            if template_file.startswith('.') or template_file.endswith('~'):
+                continue
+
+            template_name, extension = os.path.splitext(template_file)
+            extension = extension[1:] # Get rid of the leading dot.
+            template_factory = zope.component.queryUtility(
+                grok.interfaces.ITemplateFileFactory,
+                name=extension)
+
+            if template_factory is None:
+                # Warning when importing files. This should be
+                # allowed because people may be using editors that generate
+                # '.bak' files and such.
+                warnings.warn("File '%s' has an unrecognized extension in "
+                              "directory '%s'" %
+                              (template_file, template_dir), UserWarning, 2)
+                continue
+
+            inline_template = self.get(template_name)
+            if inline_template:
+                raise GrokError("Conflicting templates found for name '%s' "
+                                "in module %r, either inline and in template "
+                                "directory '%s', or two templates with the "
+                                "same name and different extensions."
+                                % (template_name, module_info.getModule(),
+                                   template_dir), inline_template)
+
+            template = template_factory(template_file, template_dir)
+            template_path = os.path.join(template_dir, template_file)
+            template._annotateGrokInfo(template_name, template_path)
+
+            self.register(template_name, template)
+
+    def listUnassociated(self):
+        for name, entry in self._reg.iteritems():
+            if not entry['associated']:
+                yield name
+
+    def checkUnassociated(self, module_info):
+        unassociated = list(self.listUnassociated())
+        if unassociated:
+            msg = (
+                "Found the following unassociated template(s) when "
+                "grokking %r: %s.  Define view classes inheriting "
+                "from grok.View to enable the template(s)." % (
+                module_info.dotted_name, ', '.join(unassociated)))
+            warnings.warn(msg, UserWarning, 1)
+
+    def checkTemplates(self, module_info, factory, component_name,
+                       has_render, has_no_render):
+        factory_name = factory.__name__.lower()
+        template_name = grok.template.bind().get(factory)
+        if template_name is None:
+            template_name = factory_name
+
+        if factory_name != template_name:
+            # grok.template is being used
+
+            if self.get(factory_name):
+                raise GrokError("Multiple possible templates for %s %r. It "
+                                "uses grok.template('%s'), but there is also "
+                                "a template called '%s'."
+                                % (component_name, factory, template_name,
+                                   factory_name), factory)
+        template = self.get(template_name)
+        if template is not None:
+            if has_render(factory):
+                # we do not accept render and template both for a view
+                # (unless it's a form, they happen to have render.
+                raise GrokError(
+                    "Multiple possible ways to render %s %r. "
+                    "It has both a 'render' method as well as "
+                    "an associated template." %
+                    (component_name, factory), factory)
+            self.markAssociated(template_name)
+            factory.template = template
+            template._initFactory(factory)
+        else:
+            if has_no_render(factory):
+                # we do not accept a view without any way to render it
+                raise GrokError("%s %r has no associated template or "
+                                "'render' method." %
+                                (component_name.title(), factory), factory)
+
+class PageTemplateFileFactory(grok.GlobalUtility):
+
+    grok.implements(grok.interfaces.ITemplateFileFactory)
+    grok.name('pt')
+
+    def __call__(self, filename, _prefix=None):
+        return grok.components.PageTemplate(filename=filename, _prefix=_prefix)


Property changes on: grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/templatereg.py
___________________________________________________________________
Name: svn:mergeinfo
   + 

Added: grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/util.py
===================================================================
--- grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/util.py	                        (rev 0)
+++ grok/branches/grokcore.xxx/devel/grokcore.view/src/grokcore/view/util.py	2008-07-17 14:19:52 UTC (rev 88444)
@@ -0,0 +1,20 @@
+import urllib
+
+from zope import component
+from zope.traversing.browser.interfaces import IAbsoluteURL
+from zope.traversing.browser.absoluteurl import _safe as SAFE_URL_CHARACTERS
+
+
+def url(request, obj, name=None, data={}):
+    url = component.getMultiAdapter((obj, request), IAbsoluteURL)()
+    if name is not None:
+        url += '/' + urllib.quote(name.encode('utf-8'), SAFE_URL_CHARACTERS)
+    if data:
+        for k, v in data.items():
+            if isinstance(v, unicode):
+                data[k] = v.encode('utf-8')
+            if isinstance(v, (list, set, tuple)):
+                data[k] = [isinstance(item, unicode) and item.encode('utf-8')
+                or item for item in v]
+        url += '?' + urllib.urlencode(data, doseq=True)
+    return url

Modified: grok/branches/grokcore.xxx/src/grok/configure.zcml
===================================================================
--- grok/branches/grokcore.xxx/src/grok/configure.zcml	2008-07-17 14:18:17 UTC (rev 88443)
+++ grok/branches/grokcore.xxx/src/grok/configure.zcml	2008-07-17 14:19:52 UTC (rev 88444)
@@ -78,7 +78,4 @@
   <!-- need to grok this for some basic REST support -->
   <grok:grok package=".rest" />
 
-  <!-- ZPT support -->
-  <grok:grok package=".templatereg" />
-
 </configure>

Modified: grok/branches/grokcore.xxx/src/grok/meta.py
===================================================================
--- grok/branches/grokcore.xxx/src/grok/meta.py	2008-07-17 14:18:17 UTC (rev 88443)
+++ grok/branches/grokcore.xxx/src/grok/meta.py	2008-07-17 14:19:52 UTC (rev 88444)
@@ -48,9 +48,10 @@
 from martian import util
 
 import grokcore.view
+import grokcore.view.templatereg
 
 import grok
-from grok import components, formlib, templatereg
+from grok import components, formlib
 from grok.util import make_checker
 from grok.interfaces import IRESTSkinType
 from grok.interfaces import IViewletManager as IGrokViewletManager
@@ -267,7 +268,7 @@
     martian.priority(1001)
 
     def grok(self, name, module, module_info, config, **kw):
-        module.__grok_templates__ = templatereg.TemplateRegistry()
+        module.__grok_templates__ = grokcore.view.templatereg.TemplateRegistry()
         return True
 
 

Modified: grok/branches/grokcore.xxx/src/grok/meta.zcml
===================================================================
--- grok/branches/grokcore.xxx/src/grok/meta.zcml	2008-07-17 14:18:17 UTC (rev 88443)
+++ grok/branches/grokcore.xxx/src/grok/meta.zcml	2008-07-17 14:19:52 UTC (rev 88444)
@@ -7,6 +7,7 @@
 
   <!-- Load the grokkers -->
   <include package="grokcore.component" file="meta.zcml" />
+  <include package="grokcore.view" file="meta.zcml" />
   <grok:grok package=".meta" />
 
 </configure>

Deleted: grok/branches/grokcore.xxx/src/grok/templatereg.py
===================================================================
--- grok/branches/grokcore.xxx/src/grok/templatereg.py	2008-07-17 14:18:17 UTC (rev 88443)
+++ grok/branches/grokcore.xxx/src/grok/templatereg.py	2008-07-17 14:19:52 UTC (rev 88444)
@@ -1,131 +0,0 @@
-from martian.error import GrokError
-from martian import util
-
-import os
-import zope.component
-import grok
-import warnings
-
-class TemplateRegistry(object):
-
-    def __init__(self):
-        self._reg = {}
-
-    def register(self, name, template):
-        self._reg[name] = dict(template=template, associated=False)
-
-    def markAssociated(self, name):
-        self._reg[name]['associated'] = True
-
-    def get(self, name):
-        entry = self._reg.get(name)
-        if entry is None:
-            return None
-        return entry['template']
-
-    def findFilesystem(self, module_info):
-        template_dir_name = grok.templatedir.bind().get(
-            module=module_info.getModule())
-        if template_dir_name is None:
-            template_dir_name = module_info.name + '_templates'
-
-        template_dir = module_info.getResourcePath(template_dir_name)
-
-        if not os.path.isdir(template_dir):
-            return
-
-        if module_info.isPackage():
-            return
-
-        for template_file in os.listdir(template_dir):
-            if template_file.startswith('.') or template_file.endswith('~'):
-                continue
-
-            template_name, extension = os.path.splitext(template_file)
-            extension = extension[1:] # Get rid of the leading dot.
-            template_factory = zope.component.queryUtility(
-                grok.interfaces.ITemplateFileFactory,
-                name=extension)
-
-            if template_factory is None:
-                # Warning when importing files. This should be
-                # allowed because people may be using editors that generate
-                # '.bak' files and such.
-                warnings.warn("File '%s' has an unrecognized extension in "
-                              "directory '%s'" %
-                              (template_file, template_dir), UserWarning, 2)
-                continue
-
-            inline_template = self.get(template_name)
-            if inline_template:
-                raise GrokError("Conflicting templates found for name '%s' "
-                                "in module %r, either inline and in template "
-                                "directory '%s', or two templates with the "
-                                "same name and different extensions."
-                                % (template_name, module_info.getModule(),
-                                   template_dir), inline_template)
-
-            template = template_factory(template_file, template_dir)
-            template_path = os.path.join(template_dir, template_file)
-            template._annotateGrokInfo(template_name, template_path)
-
-            self.register(template_name, template)
-
-    def listUnassociated(self):
-        for name, entry in self._reg.iteritems():
-            if not entry['associated']:
-                yield name
-
-    def checkUnassociated(self, module_info):
-        unassociated = list(self.listUnassociated())
-        if unassociated:
-            msg = (
-                "Found the following unassociated template(s) when "
-                "grokking %r: %s.  Define view classes inheriting "
-                "from grok.View to enable the template(s)." % (
-                module_info.dotted_name, ', '.join(unassociated)))
-            warnings.warn(msg, UserWarning, 1)
-
-    def checkTemplates(self, module_info, factory, component_name,
-                       has_render, has_no_render):
-        factory_name = factory.__name__.lower()
-        template_name = grok.template.bind().get(factory)
-        if template_name is None:
-            template_name = factory_name
-
-        if factory_name != template_name:
-            # grok.template is being used
-
-            if self.get(factory_name):
-                raise GrokError("Multiple possible templates for %s %r. It "
-                                "uses grok.template('%s'), but there is also "
-                                "a template called '%s'."
-                                % (component_name, factory, template_name,
-                                   factory_name), factory)
-        template = self.get(template_name)
-        if template is not None:
-            if has_render(factory):
-                # we do not accept render and template both for a view
-                # (unless it's a form, they happen to have render.
-                raise GrokError(
-                    "Multiple possible ways to render %s %r. "
-                    "It has both a 'render' method as well as "
-                    "an associated template." %
-                    (component_name, factory), factory)
-            self.markAssociated(template_name)
-            factory.template = template
-            template._initFactory(factory)
-        else:
-            if has_no_render(factory):
-                # we do not accept a view without any way to render it
-                raise GrokError("%s %r has no associated template or "
-                                "'render' method." %
-                                (component_name.title(), factory), factory)
-
-class PageTemplateFileFactory(grok.GlobalUtility):
-
-    grok.implements(grok.interfaces.ITemplateFileFactory)
-    grok.name('pt')
-
-    def __call__(self, filename, _prefix=None):
-        return grok.components.PageTemplate(filename=filename, _prefix=_prefix)

Modified: grok/branches/grokcore.xxx/src/grok/testing.py
===================================================================
--- grok/branches/grokcore.xxx/src/grok/testing.py	2008-07-17 14:18:17 UTC (rev 88443)
+++ grok/branches/grokcore.xxx/src/grok/testing.py	2008-07-17 14:19:52 UTC (rev 88444)
@@ -43,7 +43,7 @@
     config = ConfigurationMachine()
     zcml.do_grok('grokcore.component.meta', config)
     zcml.do_grok('grok.meta', config)
-    zcml.do_grok('grok.templatereg', config)
+    zcml.do_grok('grokcore.view.templatereg', config)
     zcml.do_grok(module_name, config)
     config.execute_actions()
 

Modified: grok/branches/grokcore.xxx/src/grok/tests/zcml/directivepackage.py
===================================================================
--- grok/branches/grokcore.xxx/src/grok/tests/zcml/directivepackage.py	2008-07-17 14:18:17 UTC (rev 88443)
+++ grok/branches/grokcore.xxx/src/grok/tests/zcml/directivepackage.py	2008-07-17 14:19:52 UTC (rev 88444)
@@ -8,7 +8,7 @@
   ...     xmlns="http://namespaces.zope.org/zope"
   ...     xmlns:grok="http://namespaces.zope.org/grok"
   ...     >
-  ...     <grok:grok package="grok.templatereg"/>
+  ...     <grok:grok package="grokcore.view.templatereg"/>
   ...     <grok:grok package="grok.tests.zcml.stoneage"/>
   ... </configure>''', context=context)
 
@@ -16,7 +16,7 @@
   >>> from grok.tests.zcml.stoneage.hunt.mammoth import Mammoth
   >>> manfred = Mammoth()
   >>> cave = Cave()
-  
+
   >>> from zope.publisher.browser import TestRequest
   >>> request = TestRequest()
   >>> from zope import component
@@ -28,7 +28,7 @@
   <h1>A comfy cave</h1>
   </body>
   </html>
-  
+
   >>> view = component.getMultiAdapter((manfred, request), name='index')
   >>> print view()
   <html>



More information about the Checkins mailing list