Пример #1
0
class FSPageTemplate(FSObject, Script, PageTemplate):
    """Wrapper for Page Template.
    """

    meta_type = 'Filesystem Page Template'
    _owner = None  # Unowned

    manage_options = (
        {
            'label': 'Customize',
            'action': 'manage_main'
        },
        {
            'label': 'Test',
            'action': 'ZScriptHTML_tryForm'
        },
    )

    security = ClassSecurityInfo()
    security.declareObjectProtected(View)

    security.declareProtected(ViewManagementScreens, 'manage_main')
    manage_main = Globals.DTMLFile('custpt', _dtmldir)

    # Declare security for unprotected PageTemplate methods.
    security.declarePrivate('pt_edit', 'write')

    def __init__(self, id, filepath, fullname=None, properties=None):
        FSObject.__init__(self, id, filepath, fullname, properties)
        self.ZBindings_edit(self._default_bindings)

    def _createZODBClone(self):
        """Create a ZODB (editable) equivalent of this object."""
        obj = ZopePageTemplate(self.getId(), self._text, self.content_type)
        obj.expand = 0
        obj.write(self.read())
        return obj


#    def ZCacheable_isCachingEnabled(self):
#        return 0

    def _readFile(self, reparse):
        """Read the data from the filesystem.
        """
        if reparse:
            file = open(self._filepath,
                        'rU')  # not 'rb', as this is a text file!
            try:
                data = file.read()
            finally:
                file.close()

            # If we already have a content_type set it must come from a
            # .metadata file and we should always honor that. The content
            # type is initialized as text/html by default, so we only
            # attempt further detection if the default is encountered.
            # One previous misbehavior remains: It is not possible to
            # force a text./html type if parsing detects it as XML.
            encoding = None
            if getattr(self, 'content_type', 'text/html') == 'text/html':
                xml_info = xml_detect_re.match(data)
                if xml_info:
                    # Smells like xml
                    # set "content_type" from the XML declaration
                    encoding = xml_info.group(1) or 'utf-8'
                    self.content_type = 'text/xml; charset=%s' % encoding

            if encoding is None:
                charset = getattr(self, 'charset', None)
                if charset is None:
                    if self.content_type.startswith('text/html'):
                        charset = charsetFromMetaEquiv(data) or 'iso-8859-15'
                    elif self.content_type.startswith('text/xml'):
                        charset = encodingFromXMLPreamble(data)
                    else:
                        raise ValueError('Unsupported content-type: %s' %
                                         self.content_type)

                if not isinstance(data, unicode):
                    data = unicode(data, charset)
            else:
                if not isinstance(data, unicode):
                    data = unicode(data, encoding)

            self.write(data)

    security.declarePrivate('read')

    def read(self):
        # Tie in on an opportunity to auto-update
        self._updateFromFS()
        return FSPageTemplate.inheritedAttribute('read')(self)

    ### The following is mainly taken from ZopePageTemplate.py ###

    expand = 0

    func_defaults = None
    func_code = ZopePageTemplate.func_code
    _default_bindings = ZopePageTemplate._default_bindings

    security.declareProtected(View, '__call__')

    def pt_macros(self):
        # Tie in on an opportunity to auto-reload
        self._updateFromFS()
        return FSPageTemplate.inheritedAttribute('pt_macros')(self)

    def pt_render(self, source=0, extra_context={}):
        self._updateFromFS()  # Make sure the template has been loaded.

        if not source:
            # If we have a conditional get, set status 304 and return
            # no content
            if _checkConditionalGET(self, extra_context):
                return ''

        result = FSPageTemplate.inheritedAttribute('pt_render')(self, source,
                                                                extra_context)
        if not source:
            _setCacheHeaders(self, extra_context)
        return result

    security.declareProtected(ViewManagementScreens, 'pt_source_file')

    def pt_source_file(self):
        """ Return a file name to be compiled into the TAL code.
        """
        return 'file:%s' % self._filepath

    security.declarePrivate('_ZPT_exec')
    _ZPT_exec = ZopePageTemplate._exec.im_func

    security.declarePrivate('_exec')

    def _exec(self, bound_names, args, kw):
        """Call a FSPageTemplate"""
        try:
            response = self.REQUEST.RESPONSE
        except AttributeError:
            response = None
        # Read file first to get a correct content_type default value.
        self._updateFromFS()

        if not kw.has_key('args'):
            kw['args'] = args
        bound_names['options'] = kw

        try:
            response = self.REQUEST.RESPONSE
            if not response.headers.has_key('content-type'):
                response.setHeader('content-type', self.content_type)
        except AttributeError:
            pass

        security = getSecurityManager()
        bound_names['user'] = security.getUser()

        # Retrieve the value from the cache.
        keyset = None
        if self.ZCacheable_isCachingEnabled():
            # Prepare a cache key.
            keyset = {
                # Why oh why?
                # All this code is cut and paste
                # here to make sure that we
                # dont call _getContext and hence can't cache
                # Annoying huh?
                'here': self.aq_parent.getPhysicalPath(),
                'bound_names': bound_names
            }
            result = self.ZCacheable_get(keywords=keyset)
            if result is not None:
                # Got a cached value.
                return result

        # Execute the template in a new security context.
        security.addContext(self)
        try:
            result = self.pt_render(extra_context=bound_names)
            if keyset is not None:
                # Store the result in the cache.
                self.ZCacheable_set(result, keywords=keyset)
            return result
        finally:
            security.removeContext(self)

        return result

    # Copy over more methods
    security.declareProtected(FTPAccess, 'manage_FTPget')
    manage_FTPget = ZopePageTemplate.manage_FTPget.im_func

    security.declareProtected(View, 'get_size')
    get_size = ZopePageTemplate.get_size.im_func
    getSize = get_size

    security.declareProtected(ViewManagementScreens, 'PrincipiaSearchSource')
    PrincipiaSearchSource = ZopePageTemplate.PrincipiaSearchSource.im_func

    security.declareProtected(ViewManagementScreens, 'document_src')
    document_src = ZopePageTemplate.document_src.im_func

    pt_getContext = ZopePageTemplate.pt_getContext.im_func

    ZScriptHTML_tryParams = ZopePageTemplate.ZScriptHTML_tryParams.im_func

    source_dot_xml = Src()
Пример #2
0
                    self.id, err_type, err_msg )
                raise RuntimeError, msg
        else:
            return FSPageTemplate.inheritedAttribute('pt_render')(self,
                source, extra_context )

    # Copy over more mothods
    security.declareProtected(FTPAccess, 'manage_FTPget')
    security.declareProtected(View, 'get_size')
    security.declareProtected(ViewManagementScreens, 'PrincipiaSearchSource',
        'document_src')

    _exec = ZopePageTemplate._exec
    pt_getContext = ZopePageTemplate.pt_getContext
    ZScriptHTML_tryParams = ZopePageTemplate.ZScriptHTML_tryParams
    manage_FTPget = ZopePageTemplate.manage_FTPget
    get_size = ZopePageTemplate.get_size
    getSize = get_size
    PrincipiaSearchSource = ZopePageTemplate.PrincipiaSearchSource
    document_src = ZopePageTemplate.document_src


d = FSPageTemplate.__dict__
d['source.xml'] = d['source.html'] = Src()

Globals.InitializeClass(FSPageTemplate)

registerFileExtension('pt', FSPageTemplate)
registerMetaType('Page Template', FSPageTemplate)

        """
        FSObject.__init__(self, id, filepath, fullname, properties)
        self.ZBindings_edit(self._default_bindings)
        self.__name__ = id
        self.title = id
        self.id = id
        self._setPropValue("content_type", "text/xml")

    def _readFile(self, reparse):
        fp = expandpath(self._filepath)
        file = open(fp, 'r')  # not 'rb', as this is a text file!
        try:
            data = file.read()
        finally:
            file.close()
        if reparse:
            self.content_type = 'text/xml'
            self.write(data)


d = FSXSLTTemplate
o = Src()
setattr(d, 'source.xml', o)
setattr(d, 'source.html', o)

InitializeClass(FSXSLTTemplate)

registerFileExtension('xsl', FSXSLTTemplate)
registerFileExtension('xslt', FSXSLTTemplate)
#registerMetaType('XSLT Template', FSXSLTTemplate)
Пример #4
0
    # Copy over more methods
    security.declareProtected(FTPAccess, 'manage_FTPget')
    manage_FTPget = ZopePageTemplate.manage_FTPget

    security.declareProtected(View, 'get_size')
    get_size = ZopePageTemplate.get_size
    getSize = get_size

    security.declareProtected(ViewManagementScreens, 'PrincipiaSearchSource')
    PrincipiaSearchSource = ZopePageTemplate.PrincipiaSearchSource

    security.declareProtected(ViewManagementScreens, 'document_src')
    document_src = ZopePageTemplate.document_src

    pt_getContext = ZopePageTemplate.pt_getContext.im_func

    ZScriptHTML_tryParams = ZopePageTemplate.ZScriptHTML_tryParams

s = Src()
setattr(FSPageTemplate, 'source.xml', s)
setattr(FSPageTemplate, 'source.html', s)
del s

Globals.InitializeClass(FSPageTemplate)

registerFileExtension('pt', FSPageTemplate)
registerFileExtension('zpt', FSPageTemplate)
registerFileExtension('html', FSPageTemplate)
registerFileExtension('htm', FSPageTemplate)
registerMetaType('Page Template', FSPageTemplate)
Пример #5
0
class FSPageTemplate(FSObject, Script, PageTemplate):
    "Wrapper for Page Template"

    meta_type = 'Filesystem Page Template'

    _owner = None  # Unowned

    manage_options = ((
        {
            'label': 'Customize',
            'action': 'manage_main'
        },
        {
            'label': 'Test',
            'action': 'ZScriptHTML_tryForm'
        },
    ) + Cacheable.manage_options)

    security = ClassSecurityInfo()
    security.declareObjectProtected(View)

    security.declareProtected(ViewManagementScreens, 'manage_main')
    manage_main = Globals.DTMLFile('dtml/custpt', globals())

    # Declare security for unprotected PageTemplate methods.
    security.declarePrivate('pt_edit', 'write')

    def __init__(self, id, filepath, fullname=None, properties=None):
        FSObject.__init__(self, id, filepath, fullname, properties)
        self.ZBindings_edit(self._default_bindings)

    def _createZODBClone(self):
        """Create a ZODB (editable) equivalent of this object."""
        obj = ZopePageTemplate(self.getId(), self._text, self.content_type)
        obj.expand = 0
        obj.write(self.read())
        return obj


#    def ZCacheable_isCachingEnabled(self):
#        return 0

    def _readFile(self, reparse):
        fp = expandpath(self._filepath)
        file = open(fp, 'r')  # not 'rb', as this is a text file!
        try:
            data = file.read()
        finally:
            file.close()
        if reparse:
            xml_info = xml_detect_re.match(data)
            if xml_info:
                # Smells like xml
                # set "content_type" from the XML declaration
                encoding = xml_info.group(1) or 'utf-8'
                self.content_type = 'text/xml; charset=%s' % encoding

            self.write(data)

    security.declarePrivate('read')

    def read(self):
        # Tie in on an opportunity to auto-update
        self._updateFromFS()
        return FSPageTemplate.inheritedAttribute('read')(self)

    ### The following is mainly taken from ZopePageTemplate.py ###

    expand = 0

    func_defaults = None
    func_code = ZopePageTemplate.func_code
    _default_bindings = ZopePageTemplate._default_bindings

    security.declareProtected(View, '__call__')

    def pt_macros(self):
        # Tie in on an opportunity to auto-reload
        self._updateFromFS()
        return FSPageTemplate.inheritedAttribute('pt_macros')(self)

    def pt_render(self, source=0, extra_context={}):
        self._updateFromFS()  # Make sure the template has been loaded.
        try:
            result = FSPageTemplate.inheritedAttribute('pt_render')(
                self, source, extra_context)
            if not source:
                _setCacheHeaders(self, extra_context)
            return result

        except RuntimeError:
            if Globals.DevelopmentMode:
                err = FSPageTemplate.inheritedAttribute('pt_errors')(self)
                if not err:
                    err = sys.exc_info()
                err_type = err[0]
                err_msg = '<pre>%s</pre>' % str(err[1]).replace("\'", "'")
                msg = 'FS Page Template %s has errors: %s.<br>%s' % (
                    self.id, err_type, html_quote(err_msg))
                raise RuntimeError, msg
            else:
                raise

    security.declareProtected(ViewManagementScreens, 'pt_source_file')

    def pt_source_file(self):
        """ Return a file name to be compiled into the TAL code.
        """
        return 'file:%s' % self._filepath

    security.declarePrivate('_ZPT_exec')
    _ZPT_exec = ZopePageTemplate._exec.im_func

    security.declarePrivate('_exec')

    def _exec(self, bound_names, args, kw):
        """Call a FSPageTemplate"""
        try:
            response = self.REQUEST.RESPONSE
        except AttributeError:
            response = None
        # Read file first to get a correct content_type default value.
        self._updateFromFS()

        if not kw.has_key('args'):
            kw['args'] = args
        bound_names['options'] = kw

        try:
            response = self.REQUEST.RESPONSE
            if not response.headers.has_key('content-type'):
                response.setHeader('content-type', self.content_type)
        except AttributeError:
            pass

        security = getSecurityManager()
        bound_names['user'] = security.getUser()

        # Retrieve the value from the cache.
        keyset = None
        if self.ZCacheable_isCachingEnabled():
            # Prepare a cache key.
            keyset = {
                # Why oh why?
                # All this code is cut and paste
                # here to make sure that we
                # dont call _getContext and hence can't cache
                # Annoying huh?
                'here': self.aq_parent.getPhysicalPath(),
                'bound_names': bound_names
            }
            result = self.ZCacheable_get(keywords=keyset)
            if result is not None:
                # Got a cached value.
                return result

        # Execute the template in a new security context.
        security.addContext(self)
        try:
            result = self.pt_render(extra_context=bound_names)
            if keyset is not None:
                # Store the result in the cache.
                self.ZCacheable_set(result, keywords=keyset)
            return result
        finally:
            security.removeContext(self)

        return result

    # Copy over more methods
    security.declareProtected(FTPAccess, 'manage_FTPget')
    manage_FTPget = ZopePageTemplate.manage_FTPget.im_func

    security.declareProtected(View, 'get_size')
    get_size = ZopePageTemplate.get_size.im_func
    getSize = get_size

    security.declareProtected(ViewManagementScreens, 'PrincipiaSearchSource')
    PrincipiaSearchSource = ZopePageTemplate.PrincipiaSearchSource.im_func

    security.declareProtected(ViewManagementScreens, 'document_src')
    document_src = ZopePageTemplate.document_src.im_func

    pt_getContext = ZopePageTemplate.pt_getContext.im_func

    ZScriptHTML_tryParams = ZopePageTemplate.ZScriptHTML_tryParams.im_func

    source_dot_xml = Src()