[Zope-Checkins] SVN: Zope/branches/ajung-zpt-integration/lib/python/Products/ZPT/ZPT.py moooooooooooore cleanup...the code *look* less scary (but it remains scary)

Andreas Jung andreas at andreas-jung.com
Fri Dec 9 10:43:46 EST 2005


Log message for revision 40661:
  moooooooooooore cleanup...the code *look* less scary (but it remains scary)
  

Changed:
  U   Zope/branches/ajung-zpt-integration/lib/python/Products/ZPT/ZPT.py

-=-
Modified: Zope/branches/ajung-zpt-integration/lib/python/Products/ZPT/ZPT.py
===================================================================
--- Zope/branches/ajung-zpt-integration/lib/python/Products/ZPT/ZPT.py	2005-12-09 15:30:22 UTC (rev 40660)
+++ Zope/branches/ajung-zpt-integration/lib/python/Products/ZPT/ZPT.py	2005-12-09 15:43:46 UTC (rev 40661)
@@ -10,49 +10,42 @@
 # FOR A PARTICULAR PURPOSE
 #
 ##############################################################################
-"""Zope Page Template module
 
-Zope object encapsulating a Page Template.
-"""
 
+""" Zope Page Template module (wrapper for the Zope 3 ZPT implementation) """
+
 __version__='$Revision: 1.48 $'[11:-2]
 
-import os, AccessControl, Acquisition, sys, types
-from types import StringType
-from Globals import DTMLFile, ImageFile, MessageDialog, package_home
-from zLOG import LOG, ERROR, INFO
+from urllib import quote
+import os, AccessControl, Acquisition 
+from Globals import ImageFile, package_home, InitializeClass
 from OFS.SimpleItem import SimpleItem
 from DateTime.DateTime import DateTime
-from Shared.DC.Scripts.Script import Script, BindingsUI
+from Shared.DC.Scripts.Script import Script 
 from Shared.DC.Scripts.Signature import FuncCode
 from AccessControl import getSecurityManager
-try:
-    from AccessControl import Unauthorized
-except ImportError:
-    Unauthorized = "Unauthorized"
+
 from OFS.History import Historical, html_diff
 from OFS.Cache import Cacheable
 from OFS.Traversable import Traversable
 from OFS.PropertyManager import PropertyManager
-#from PageTemplate import PageTemplate
+
 from Products.PageTemplates.Expressions import SecureModuleImporter
 from Products.PageTemplates.PageTemplateFile import PageTemplateFile
 
-try:
-    from webdav.Lockable import ResourceLockedError
-    from webdav.WriteLockInterface import WriteLockInterface
-    SUPPORTS_WEBDAV_LOCKS = 1
-except ImportError:
-    SUPPORTS_WEBDAV_LOCKS = 0
+from AccessControl import Unauthorized
+from AccessControl.Permissions import view, ftp_access, change_page_templates, view_management_screens
 
+from webdav.Lockable import ResourceLockedError
+from webdav.WriteLockInterface import WriteLockInterface
 
 from zope.pagetemplate.pagetemplate import PageTemplate
 
 class Src(Acquisition.Explicit):
-    " "
+    """ I am scary code """
 
+    index_html = None
     PUT = document_src = Acquisition.Acquired
-    index_html = None
 
     def __before_publishing_traverse__(self, ob, request):
         if getattr(request, '_hacked_path', 0):
@@ -65,10 +58,9 @@
 
 class ZPT(Script, PageTemplate, Historical, Cacheable,
                        Traversable, PropertyManager):
-    "Zope wrapper for Page Template using TAL, TALES, and METAL"
+    """ Z2 wrapper class for Zope 3 page templates """
 
-    if SUPPORTS_WEBDAV_LOCKS:
-        __implements__ = (WriteLockInterface,)
+    __implements__ = (WriteLockInterface,)
 
     meta_type = 'ZPT'
 
@@ -77,7 +69,7 @@
 
     _default_bindings = {'name_subpath': 'traverse_subpath'}
     _default_content_fn = os.path.join(package_home(globals()),
-                                       'www', 'default.html')
+                                       'pt', 'default.html')
 
     manage_options = (
         {'label':'Edit', 'action':'pt_editForm',
@@ -88,11 +80,16 @@
         + SimpleItem.manage_options \
         + Cacheable.manage_options
 
+
     _properties=({'id':'title', 'type': 'string', 'mode': 'wd'},
                  {'id':'content_type', 'type':'string', 'mode': 'w'},
                  {'id':'expand', 'type':'boolean', 'mode': 'w'},
                  )
 
+    security = AccessControl.ClassSecurityInfo()
+    security.declareObjectProtected(view)
+    security.declareProtected(view, '__call__')
+
     def __init__(self, id, text=None, content_type=None):
         self.id = str(id)
         self.ZBindings_edit(self._default_bindings)
@@ -104,33 +101,17 @@
         PropertyManager._setPropValue(self, id, value)
         self.ZCacheable_invalidate()
 
-    security = AccessControl.ClassSecurityInfo()
 
-    security.declareObjectProtected('View')
-    security.declareProtected('View', '__call__')
 
-    security.declareProtected('View management screens',
-      'pt_editForm', 'manage_main', 'read',
-      'ZScriptHTML_tryForm', 'PrincipiaSearchSource',
-      'document_src', 'source_dot_xml')
+    security.declareProtected(change_page_templates, 'pt_edit')
+    def pt_edit(self, text, content_type):
+        PageTemplate.pt_edit(self, text, content_type)
 
-    security.declareProtected('FTP access',
-      'manage_FTPstat','manage_FTPget','manage_FTPlist')
-
-    pt_editForm = PageTemplateFile('www/ptEdit', globals(),
-                                   __name__='pt_editForm')
-    pt_editForm._owner = None
-    manage = manage_main = pt_editForm
-
-    source_dot_xml = Src()
-
-    security.declareProtected('Change Page Templates',
-      'pt_editAction', 'pt_setTitle', 'pt_edit',
-      'pt_upload', 'pt_changePrefs')
+    security.declareProtected(change_page_templates, 'pt_editAction')
     def pt_editAction(self, REQUEST, title, text, content_type, expand):
         """Change the title and document."""
-        if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked():
-            raise ResourceLockedError, "File is locked via WebDAV"
+        if self.wl_isLocked():
+            raise ResourceLockedError("File is locked via WebDAV")
         self.expand=expand
         self.pt_setTitle(title)
         self.pt_edit(text, content_type)
@@ -142,25 +123,28 @@
                        % '<br>'.join(self._v_warnings))
         return self.pt_editForm(manage_tabs_message=message)
 
+
+    security.declareProtected(change_page_templates, 'pt_setTitle')
     def pt_setTitle(self, title):
         charset = getattr(self, 'management_page_charset', None)
-        if type(title) == types.StringType and charset:
+        if isinstance(title, str) and charset:
             try:
                 title.decode('us-ascii')
                 title = str(title)
             except UnicodeError:
                 title = unicode(title, charset)
-        elif type(title) != types.UnicodeType:
+        elif not isinstance(title, unicode):
             title = str(title)
         self._setPropValue('title', title)
 
+    security.declareProtected(change_page_templates, 'pt_upload')
     def pt_upload(self, REQUEST, file='', charset=None):
         """Replace the document with the text in file."""
-        if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked():
-            raise ResourceLockedError, "File is locked via WebDAV"
+        if self.wl_isLocked():
+            raise ResourceLockedError("File is locked via WebDAV")
 
-        if type(file) is not StringType:
-            if not file: raise ValueError, 'File not specified'
+        if not isinstance(file, str):
+            if not file: raise ValueError('File not specified')
             file = file.read()
         if charset:
             try:
@@ -172,6 +156,7 @@
         message = 'Saved changes.'
         return self.pt_editForm(manage_tabs_message=message)
 
+    security.declareProtected(change_page_templates, 'pt_changePrefs')
     def pt_changePrefs(self, REQUEST, height=None, width=None,
                        dtpref_cols="100%", dtpref_rows="20"):
         """Change editing preferences."""
@@ -220,11 +205,16 @@
              }
         return c
 
-#    def write(self, text):
-#        self.ZCacheable_invalidate()
-##        ZopePageTemplate.inheritedAttribute('write')(self, text)
-#        self.pt_edit(text, self.content_type)
+    security.declareProtected(change_page_templates, 'write')
+    def write(self, text):
+        self.ZCacheable_invalidate()
+        PageTemplate.write(self, text)
 
+    security.declareProtected(view_management_screens, 'manage_main', 'read',
+      'ZScriptHTML_tryForm')
+
+
+
     def _exec(self, bound_names, args, kw):
         """Call a Page Template"""
         if not kw.has_key('args'):
@@ -254,7 +244,9 @@
 
         # Execute the template in a new security context.
         security.addContext(self)
+
         try:
+            # XXX: check the parameters for pt_render()! (aj)
             result = self.pt_render(self.pt_getContext())
 
 #            result = self.pt_render(extra_context=bound_names)
@@ -265,35 +257,43 @@
         finally:
             security.removeContext(self)
 
-    security.declareProtected('Change Page Templates',
-      'PUT', 'manage_FTPput', 'write',
+    security.declareProtected(change_page_templates,
       'manage_historyCopy',
       'manage_beforeHistoryCopy', 'manage_afterHistoryCopy')
 
+    security.declareProtected(change_page_templates, 'PUT')
     def PUT(self, REQUEST, RESPONSE):
         """ Handle HTTP PUT requests """
         self.dav__init(REQUEST, RESPONSE)
-        if SUPPORTS_WEBDAV_LOCKS:
-            self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1)
+        self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1)
         self.write(REQUEST.get('BODY', ''))
         RESPONSE.setStatus(204)
         return RESPONSE
 
+    security.declareProtected(change_page_templates, 'manage_FTPput')
     manage_FTPput = PUT
 
+    security.declareProtected(ftp_access, 'manage_FTPstat','manage_FTPlist')
+
+    security.declareProtected(ftp_access, 'manage_FTPget')
     def manage_FTPget(self):
         "Get source for FTP download"
         self.REQUEST.RESPONSE.setHeader('Content-Type', self.content_type)
         return self.read()
 
+    security.declareProtected(view_management_screens, 'get_size')
     def get_size(self):
         return len(self.read())
+
+    security.declareProtected(view_management_screens, 'getSize')
     getSize = get_size
 
+    security.declareProtected(view_management_screens, 'PrincipiaSearchSource')
     def PrincipiaSearchSource(self):
         "Support for searching - the document's contents are searched."
         return self.read()
 
+    security.declareProtected(view_management_screens, 'document_src')
     def document_src(self, REQUEST=None, RESPONSE=None):
         """Return expanded document source."""
 
@@ -324,18 +324,29 @@
             # acquisition context, so we don't know where it is. :-(
             return None
 
-    if not SUPPORTS_WEBDAV_LOCKS:
-        def wl_isLocked(self):
-            return 0
+    def wl_isLocked(self):
+        return 0
 
-#setattr(ZopePageTemplate, 'source.xml',  ZopePageTemplate.source_dot_xml)
-#setattr(ZopePageTemplate, 'source.html', ZopePageTemplate.source_dot_xml)
+    security.declareProtected(view_management_screens, 'source_dot_xml')
+    source_dot_xml = Src()
 
+    security.declareProtected(view_management_screens, 'pt_editForm')
+    pt_editForm = PageTemplateFile('pt/ptEdit', globals(),
+                                   __name__='pt_editForm')
+    pt_editForm._owner = None
+    manage = manage_main = pt_editForm
+
+
+InitializeClass(ZPT)
+
+
+setattr(ZPT, 'source.xml',  ZPT.source_dot_xml)
+setattr(ZPT, 'source.html', ZPT.source_dot_xml)
+
 # Product registration and Add support
 manage_addZPTForm= PageTemplateFile(
-    'www/ptAdd', globals(), __name__='manage_addPageTemplateForm')
+    'pt/ptAdd', globals(), __name__='manage_addPageTemplateForm')
 
-from urllib import quote
 
 def manage_addZPT(self, id, title=None, text=None,
                            REQUEST=None, submit=None):
@@ -374,7 +385,7 @@
     return ''
 
 from Products.PageTemplates import misc_
-misc_['exclamation.gif'] = ImageFile('www/exclamation.gif', globals())
+misc_['exclamation.gif'] = ImageFile('pt/exclamation.gif', globals())
 
 def initialize(context):
     context.registerClass(
@@ -382,7 +393,7 @@
         permission='Add Page Templates',
         constructors=(manage_addZPTForm,
                       manage_addZPT),
-        icon='www/zpt.gif',
+        icon='pt/zpt.gif',
         )
     context.registerHelp()
     context.registerHelpTitle('Zope Help')



More information about the Zope-Checkins mailing list