Commit 695ee1d0 authored by Boxiang Sun's avatar Boxiang Sun

forward to DocumentTemplate 4.0

parent c0167bef
Changelog
=========
3.0 (unreleased)
----------------
- Replace C code with a pure-Python implementation.
- Add `__contains__` support to DocumentTemplate.TemplateDict.
- Modernised C code in preparation of porting to Python 3.
2.13.2 (2011-12-12)
-------------------
......
include *.rst
include *.txt
recursive-include include *
......
Metadata-Version: 1.0
Name: DocumentTemplate
Version: 2.13.2
Summary: Document Templating Markup Language (DTML)
Home-page: http://pypi.python.org/pypi/DocumentTemplate
Author: Zope Foundation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: Overview
========
This package implements the original Document Templating Markup Language
(DTML). It uses custom SGML tags to implement simple programmatic features,
such as variable replacement, conditional logic and loops.
Inside Zope environments page templates and TAL have superseded DTML for most
use cases.
Changelog
=========
2.13.2 (2011-12-12)
-------------------
- Restrict the available functions in `DocumentTemplate.sequence` to public
API's of `zope.sequencesort`.
2.13.1 (2010-07-15)
-------------------
- LP #143273: Enable the dtml-var modifiers url_quote, url_unquote,
url_quote_plus and url_unquote_plus to handle unicode strings.
2.13.0 (2010-06-19)
-------------------
- Released as separate package.
Platform: UNKNOWN
......@@ -16,106 +16,174 @@
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
$Id: bootstrap.py 108946 2010-02-12 02:40:18Z yusei $
"""
import os, shutil, sys, tempfile, urllib2
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
is_jython = sys.platform.startswith('java')
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --find-links to point to local resources, you can keep
this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", help="use a specific zc.buildout version")
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
parser.add_option("--allow-site-packages",
action="store_true", default=False,
help=("Let bootstrap.py use existing site packages"))
parser.add_option("--setuptools-version",
help="use a specific setuptools version")
# parsing arguments
parser = OptionParser()
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="distribute", default=False,
help="Use Distribute rather than Setuptools.")
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.version is not None:
VERSION = '==%s' % options.version
else:
VERSION = ''
######################################################################
# load/install setuptools
USE_DISTRIBUTE = options.distribute
args = args + ['bootstrap']
to_reload = False
try:
import pkg_resources
if not hasattr(pkg_resources, '_distribute'):
to_reload = True
raise ImportError
except ImportError:
ez = {}
if USE_DISTRIBUTE:
exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True)
else:
exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
if to_reload:
reload(pkg_resources)
else:
if options.allow_site_packages:
import setuptools
import pkg_resources
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
def quote (c):
return c
cmd = 'from setuptools.command.easy_install import main; main()'
ws = pkg_resources.working_set
if USE_DISTRIBUTE:
requirement = 'distribute'
else:
requirement = 'setuptools'
if is_jython:
import subprocess
assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd',
quote(tmpeggs), 'zc.buildout' + VERSION],
env=dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
).wait() == 0
else:
assert os.spawnle(
os.P_WAIT, sys.executable, quote (sys.executable),
'-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION,
dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
) == 0
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
ez = {}
exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez)
if not options.allow_site_packages:
# ez_setup imports site, which adds site packages
# this will remove them from the path to ensure that incompatible versions
# of setuptools are not in the path
import site
# inside a virtualenv, there is no 'getsitepackages'.
# We can't remove these reliably
if hasattr(site, 'getsitepackages'):
for sitepackage_path in site.getsitepackages():
sys.path[:] = [x for x in sys.path if sitepackage_path not in x]
setup_args = dict(to_dir=tmpeggs, download_delay=0)
if options.setuptools_version is not None:
setup_args['version'] = options.setuptools_version
ez['use_setuptools'](**setup_args)
import setuptools
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
######################################################################
# Install buildout
ws = pkg_resources.working_set
cmd = [sys.executable, '-c',
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
setuptools_path = ws.find(
pkg_resources.Requirement.parse('setuptools')).location
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
try:
return not parsed_version.is_prerelease
except AttributeError:
# Older setuptools
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setuptools_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
import subprocess
if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0:
raise Exception(
"Failed to execute command:\n%s" % repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require('zc.buildout' + VERSION)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs)
[buildout]
extends = https://raw.githubusercontent.com/zopefoundation/Zope/master/versions.cfg
develop = .
parts = interpreter test
parts = tox interpreter test
[versions]
DocumentTemplate =
[tox]
recipe = zc.recipe.egg
eggs = tox
[interpreter]
recipe = zc.recipe.egg
......
This diff is collapsed.
This diff is collapsed.
##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""ExtensionClass
Extension Class exists to support types derived from the old ExtensionType
meta-class that preceeded Python 2.2 and new-style classes.
As a meta-class, ExtensionClass provides the following features:
- Support for a class initialiser:
>>> from ExtensionClass import ExtensionClass, Base
>>> class C(Base):
... def __class_init__(self):
... print 'class init called'
... print self.__name__
... def bar(self):
... return 'bar called'
class init called
C
>>> c = C()
>>> int(c.__class__ is C)
1
>>> int(c.__class__ is type(c))
1
- Making sure that every instance of the meta-class has Base as a base class:
>>> class X:
... __metaclass__ = ExtensionClass
>>> Base in X.__mro__
1
- Provide an inheritedAttribute method for looking up attributes in
base classes:
>>> class C2(C):
... def bar(*a):
... return C2.inheritedAttribute('bar')(*a), 42
class init called
C2
>>> o = C2()
>>> o.bar()
('bar called', 42)
This is for compatability with old code. New code should use super
instead.
The base class, Base, exists mainly to support the __of__ protocol.
The __of__ protocol is similar to __get__ except that __of__ is called
when an implementor is retrieved from an instance as well as from a
class:
>>> class O(Base):
... def __of__(*a):
... return a
>>> o1 = O()
>>> o2 = O()
>>> C.o1 = o1
>>> c.o2 = o2
>>> c.o1 == (o1, c)
1
>>> C.o1 == o1
1
>>> int(c.o2 == (o2, c))
1
We accomplish this by making a class that implements __of__ a
descriptor and treating all descriptor ExtensionClasses this way. That
is, if an extension class is a descriptor, it's __get__ method will be
called even when it is retrieved from an instance.
>>> class O(Base):
... def __get__(*a):
... return a
...
>>> o1 = O()
>>> o2 = O()
>>> C.o1 = o1
>>> c.o2 = o2
>>> int(c.o1 == (o1, c, type(c)))
1
>>> int(C.o1 == (o1, None, type(c)))
1
>>> int(c.o2 == (o2, c, type(c)))
1
$Id: __init__.py 110581 2010-04-07 15:04:20Z tseaver $
"""
from _ExtensionClass import *
/*
Copyright (c) 2003 Zope Foundation and Contributors.
All Rights Reserved.
This software is subject to the provisions of the Zope Public License,
Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
FOR A PARTICULAR PURPOSE.
*/
/*
Reusable pickle support code
This is "includeware", meant to be used through a C include
*/
/* It's a dang shame we can't inherit __get/setstate__ from object :( */
static PyObject *str__slotnames__, *copy_reg_slotnames, *__newobj__;
static PyObject *str__getnewargs__, *str__getstate__;
#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
typedef int Py_ssize_t;
#define PY_SSIZE_T_MAX INT_MAX
#define PY_SSIZE_T_MIN INT_MIN
#endif
static int
pickle_setup(void)
{
PyObject *copy_reg;
int r = -1;
#define DEFINE_STRING(S) \
if(! (str ## S = PyString_FromString(# S))) return -1
DEFINE_STRING(__slotnames__);
DEFINE_STRING(__getnewargs__);
DEFINE_STRING(__getstate__);
#undef DEFINE_STRING
copy_reg = PyImport_ImportModule("copy_reg");
if (copy_reg == NULL)
return -1;
copy_reg_slotnames = PyObject_GetAttrString(copy_reg, "_slotnames");
if (copy_reg_slotnames == NULL)
goto end;
__newobj__ = PyObject_GetAttrString(copy_reg, "__newobj__");
if (__newobj__ == NULL)
goto end;
r = 0;
end:
Py_DECREF(copy_reg);
return r;
}
static PyObject *
pickle_slotnames(PyTypeObject *cls)
{
PyObject *slotnames;
slotnames = PyDict_GetItem(cls->tp_dict, str__slotnames__);
if (slotnames != NULL)
{
Py_INCREF(slotnames);
return slotnames;
}
slotnames = PyObject_CallFunctionObjArgs(copy_reg_slotnames, (PyObject*)cls,
NULL);
if (slotnames != NULL &&
slotnames != Py_None &&
! PyList_Check(slotnames))
{
PyErr_SetString(PyExc_TypeError,
"copy_reg._slotnames didn't return a list or None");
Py_DECREF(slotnames);
slotnames = NULL;
}
return slotnames;
}
static PyObject *
pickle_copy_dict(PyObject *state)
{
PyObject *copy, *key, *value;
char *ckey;
Py_ssize_t pos = 0;
Py_ssize_t nr;
copy = PyDict_New();
if (copy == NULL)
return NULL;
if (state == NULL)
return copy;
while ((nr = PyDict_Next(state, &pos, &key, &value)))
{
if (nr < 0)
goto err;
if (key && PyString_Check(key))
{
ckey = PyString_AS_STRING(key);
if (*ckey == '_' &&
(ckey[1] == 'v' || ckey[1] == 'p') &&
ckey[2] == '_')
/* skip volatile and persistent */
continue;
}
if (key != NULL && value != NULL &&
(PyObject_SetItem(copy, key, value) < 0)
)
goto err;
}
return copy;
err:
Py_DECREF(copy);
return NULL;
}
static char pickle___getstate__doc[] =
"Get the object serialization state\n"
"\n"
"If the object has no assigned slots and has no instance dictionary, then \n"
"None is returned.\n"
"\n"
"If the object has no assigned slots and has an instance dictionary, then \n"
"the a copy of the instance dictionary is returned. The copy has any items \n"
"with names starting with '_v_' or '_p_' ommitted.\n"
"\n"
"If the object has assigned slots, then a two-element tuple is returned. \n"
"The first element is either None or a copy of the instance dictionary, \n"
"as described above. The second element is a dictionary with items \n"
"for each of the assigned slots.\n"
;
static PyObject *
pickle___getstate__(PyObject *self)
{
PyObject *slotnames=NULL, *slots=NULL, *state=NULL;
PyObject **dictp;
int n=0;
slotnames = pickle_slotnames(self->ob_type);
if (slotnames == NULL)
return NULL;
dictp = _PyObject_GetDictPtr(self);
if (dictp)
state = pickle_copy_dict(*dictp);
else
{
state = Py_None;
Py_INCREF(state);
}
if (slotnames != Py_None)
{
int i;
slots = PyDict_New();
if (slots == NULL)
goto end;
for (i = 0; i < PyList_GET_SIZE(slotnames); i++)
{
PyObject *name, *value;
char *cname;
name = PyList_GET_ITEM(slotnames, i);
if (PyString_Check(name))
{
cname = PyString_AS_STRING(name);
if (*cname == '_' &&
(cname[1] == 'v' || cname[1] == 'p') &&
cname[2] == '_')
/* skip volatile and persistent */
continue;
}
value = PyObject_GetAttr(self, name);
if (value == NULL)
PyErr_Clear();
else
{
int err = PyDict_SetItem(slots, name, value);
Py_DECREF(value);
if (err)
goto end;
n++;
}
}
}
if (n)
state = Py_BuildValue("(NO)", state, slots);
end:
Py_XDECREF(slotnames);
Py_XDECREF(slots);
return state;
}
static int
pickle_setattrs_from_dict(PyObject *self, PyObject *dict)
{
PyObject *key, *value;
Py_ssize_t pos = 0;
if (! PyDict_Check(dict))
{
PyErr_SetString(PyExc_TypeError, "Expected dictionary");
return -1;
}
while (PyDict_Next(dict, &pos, &key, &value))
{
if (key != NULL && value != NULL &&
(PyObject_SetAttr(self, key, value) < 0)
)
return -1;
}
return 0;
}
static char pickle___setstate__doc[] =
"Set the object serialization state\n"
"\n"
"The state should be in one of 3 forms:\n"
"\n"
"- None\n"
"\n"
" Ignored\n"
"\n"
"- A dictionary\n"
"\n"
" In this case, the object's instance dictionary will be cleared and \n"
" updated with the new state.\n"
"\n"
"- A two-tuple with a string as the first element. \n"
"\n"
" In this case, the method named by the string in the first element will be\n"
" called with the second element.\n"
"\n"
" This form supports migration of data formats.\n"
"\n"
"- A two-tuple with None or a Dictionary as the first element and\n"
" with a dictionary as the second element.\n"
"\n"
" If the first element is not None, then the object's instance dictionary \n"
" will be cleared and updated with the value.\n"
"\n"
" The items in the second element will be assigned as attributes.\n"
;
static PyObject *
pickle___setstate__(PyObject *self, PyObject *state)
{
PyObject *slots=NULL;
if (PyTuple_Check(state))
{
if (! PyArg_ParseTuple(state, "OO", &state, &slots))
return NULL;
}
if (state != Py_None)
{
PyObject **dict;
dict = _PyObject_GetDictPtr(self);
if (dict)
{
if (*dict == NULL)
{
*dict = PyDict_New();
if (*dict == NULL)
return NULL;
}
}
if (*dict != NULL)
{
PyDict_Clear(*dict);
if (PyDict_Update(*dict, state) < 0)
return NULL;
}
else if (pickle_setattrs_from_dict(self, state) < 0)
return NULL;
}
if (slots != NULL && pickle_setattrs_from_dict(self, slots) < 0)
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
static char pickle___reduce__doc[] =
"Reduce an object to contituent parts for serialization\n"
;
static PyObject *
pickle___reduce__(PyObject *self)
{
PyObject *args=NULL, *bargs=0, *state=NULL;
int l, i;
/* we no longer require '__getnewargs__' to be defined but use it if it is */
PyObject *getnewargs=NULL;
getnewargs = PyObject_GetAttr(self, str__getnewargs__);
if (getnewargs)
bargs = PyEval_CallObject(getnewargs, (PyObject *)NULL);
else {
PyErr_Clear();
bargs = PyTuple_New(0);
}
l = PyTuple_Size(bargs);
if (l < 0)
goto end;
args = PyTuple_New(l+1);
if (args == NULL)
goto end;
Py_INCREF(self->ob_type);
PyTuple_SET_ITEM(args, 0, (PyObject*)(self->ob_type));
for (i = 0; i < l; i++)
{
Py_INCREF(PyTuple_GET_ITEM(bargs, i));
PyTuple_SET_ITEM(args, i+1, PyTuple_GET_ITEM(bargs, i));
}
state = PyObject_CallMethodObjArgs(self, str__getstate__, NULL);
if (state == NULL)
goto end;
state = Py_BuildValue("(OON)", __newobj__, args, state);
end:
Py_XDECREF(bargs);
Py_XDECREF(args);
Py_XDECREF(getnewargs);
return state;
}
#define PICKLE_GETSTATE_DEF \
{"__getstate__", (PyCFunction)pickle___getstate__, METH_NOARGS, \
pickle___getstate__doc},
#define PICKLE_SETSTATE_DEF \
{"__setstate__", (PyCFunction)pickle___setstate__, METH_O, \
pickle___setstate__doc},
#define PICKLE_GETNEWARGS_DEF
#define PICKLE_REDUCE_DEF \
{"__reduce__", (PyCFunction)pickle___reduce__, METH_NOARGS, \
pickle___reduce__doc},
#define PICKLE_METHODS PICKLE_GETSTATE_DEF PICKLE_SETSTATE_DEF \
PICKLE_GETNEWARGS_DEF PICKLE_REDUCE_DEF
This diff is collapsed.
[egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0
[check-manifest]
ignore =
*.cfg
bootstrap.py
[flake8]
ignore = N801,N802,N803,N805,N806,N812,E301
exclude = bootstrap.py
......@@ -12,34 +12,43 @@
#
##############################################################################
from os.path import join
from setuptools import setup, find_packages, Extension
from setuptools import setup, find_packages
setup(name='DocumentTemplate',
version = '2.13.2',
version='3.0.dev0',
url='http://pypi.python.org/pypi/DocumentTemplate',
license='ZPL 2.1',
description="Document Templating Markup Language (DTML)",
author='Zope Foundation and Contributors',
author_email='zope-dev@zope.org',
long_description=open('README.txt').read() + '\n' +
open('CHANGES.txt').read(),
long_description=(open('README.rst').read() + '\n' +
open('CHANGES.rst').read()),
packages=find_packages('src'),
package_dir={'': 'src'},
ext_modules=[Extension(
name='DocumentTemplate.cDocumentTemplate',
include_dirs=['include', 'src'],
sources=[join('src', 'DocumentTemplate', 'cDocumentTemplate.c')],
depends=[join('include', 'ExtensionClass', 'ExtensionClass.h')]),
classifiers=[
"Development Status :: 6 - Mature",
"Environment :: Web Environment",
"Framework :: Zope2",
"License :: OSI Approved :: Zope Public License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
# "Programming Language :: Python :: 3.3",
# "Programming Language :: Python :: 3.4",
# "Programming Language :: Python :: 3.5",
"Programming Language :: Python :: Implementation :: CPython",
# "Programming Language :: Python :: Implementation :: PyPy",
],
install_requires=[
'AccessControl',
'Acquisition',
'ExtensionClass',
'RestrictedPython',
'zExceptions',
'zope.sequencesort',
'zope.structuredtext',
'AccessControl',
'Acquisition',
'ExtensionClass>=4.1a1',
'RestrictedPython',
'six',
'zExceptions',
'zope.sequencesort',
'zope.structuredtext',
],
include_package_data=True,
zip_safe=False,
......
Metadata-Version: 1.0
Name: DocumentTemplate
Version: 2.13.2
Summary: Document Templating Markup Language (DTML)
Home-page: http://pypi.python.org/pypi/DocumentTemplate
Author: Zope Foundation and Contributors
Author-email: zope-dev@zope.org
License: ZPL 2.1
Description: Overview
========
This package implements the original Document Templating Markup Language
(DTML). It uses custom SGML tags to implement simple programmatic features,
such as variable replacement, conditional logic and loops.
Inside Zope environments page templates and TAL have superseded DTML for most
use cases.
Changelog
=========
2.13.2 (2011-12-12)
-------------------
- Restrict the available functions in `DocumentTemplate.sequence` to public
API's of `zope.sequencesort`.
2.13.1 (2010-07-15)
-------------------
- LP #143273: Enable the dtml-var modifiers url_quote, url_unquote,
url_quote_plus and url_unquote_plus to handle unicode strings.
2.13.0 (2010-06-19)
-------------------
- Released as separate package.
Platform: UNKNOWN
CHANGES.txt
COPYRIGHT.txt
LICENSE.txt
MANIFEST.in
README.txt
bootstrap.py
buildout.cfg
setup.py
include/ExtensionClass/ExtensionClass.h
include/ExtensionClass/_ExtensionClass.c
include/ExtensionClass/__init__.py
include/ExtensionClass/tests.py
include/ExtensionClass/pickle/pickle.c
src/DocumentTemplate/DT_HTML.py
src/DocumentTemplate/DT_If.py
src/DocumentTemplate/DT_In.py
src/DocumentTemplate/DT_InSV.py
src/DocumentTemplate/DT_Let.py
src/DocumentTemplate/DT_Raise.py
src/DocumentTemplate/DT_Return.py
src/DocumentTemplate/DT_String.py
src/DocumentTemplate/DT_Try.py
src/DocumentTemplate/DT_UI.py
src/DocumentTemplate/DT_Util.py
src/DocumentTemplate/DT_Var.py
src/DocumentTemplate/DT_With.py
src/DocumentTemplate/DTtestExpr.py
src/DocumentTemplate/Let.stx
src/DocumentTemplate/VSEval.py
src/DocumentTemplate/_DocumentTemplate.py
src/DocumentTemplate/__init__.py
src/DocumentTemplate/cDocumentTemplate.c
src/DocumentTemplate/html_quote.py
src/DocumentTemplate/pDocumentTemplate.py
src/DocumentTemplate/permissions.py
src/DocumentTemplate/security.py
src/DocumentTemplate/ustr.py
src/DocumentTemplate.egg-info/PKG-INFO
src/DocumentTemplate.egg-info/SOURCES.txt
src/DocumentTemplate.egg-info/dependency_links.txt
src/DocumentTemplate.egg-info/not-zip-safe
src/DocumentTemplate.egg-info/requires.txt
src/DocumentTemplate.egg-info/top_level.txt
src/DocumentTemplate/sequence/SortEx.py
src/DocumentTemplate/sequence/__init__.py
src/DocumentTemplate/sequence/tests/__init__.py
src/DocumentTemplate/sequence/tests/results.py
src/DocumentTemplate/sequence/tests/testSequence.py
src/DocumentTemplate/sequence/tests/ztestlib.py
src/DocumentTemplate/tests/__init__.py
src/DocumentTemplate/tests/dealers.dtml
src/DocumentTemplate/tests/dealers.out
src/DocumentTemplate/tests/testDTML.py
src/DocumentTemplate/tests/testDTMLUnicode.py
src/DocumentTemplate/tests/testSecurity.py
src/DocumentTemplate/tests/test_DT_Raise.py
src/DocumentTemplate/tests/test_DT_Var.py
src/DocumentTemplate/tests/testustr.py
src/TreeDisplay/TreeTag.py
src/TreeDisplay/__init__.py
src/TreeDisplay/www/Blank_icon.gif
src/TreeDisplay/www/Minus_icon.gif
src/TreeDisplay/www/Plus_icon.gif
\ No newline at end of file
AccessControl
Acquisition
ExtensionClass
RestrictedPython
zExceptions
zope.sequencesort
zope.structuredtext
\ No newline at end of file
This diff is collapsed.
......@@ -10,7 +10,7 @@
# FOR A PARTICULAR PURPOSE
#
##############################################################################
__doc__='''Conditional insertion
'''Conditional insertion
Conditional insertion is performed using 'if' and 'else'
commands.
......@@ -75,65 +75,78 @@ __doc__='''Conditional insertion
variable is not reevaluated.
'''
__rcs_id__='$Id: DT_If.py 110402 2010-04-01 16:04:02Z tseaver $'
__version__='$Revision: 1.19 $'[11:-2]
from DocumentTemplate.DT_Util import ParseError, parse_params, name_param, str
from DocumentTemplate.DT_Util import (
name_param,
ParseError,
parse_params,
)
class If:
blockContinuations='else','elif'
name='if'
elses=None
expr=''
class If(object):
blockContinuations = ('else', 'elif')
name = 'if'
elses = None
expr = ''
def __init__(self, blocks):
tname, args, section = blocks[0]
args=parse_params(args, name='', expr='')
name,expr=name_param(args,'if',1)
self.__name__= name
if expr is None: cond=name
else: cond=expr.eval
sections=[cond, section.blocks]
if blocks[-1][0]=='else':
args = parse_params(args, name='', expr='')
name, expr = name_param(args, 'if', 1)
self.__name__ = name
if expr is None:
cond = name
else:
cond = expr.eval
sections = [cond, section.blocks]
if blocks[-1][0] == 'else':
tname, args, section = blocks[-1]
del blocks[-1]
args=parse_params(args, name='')
args = parse_params(args, name='')
if args:
ename,expr=name_param(args,'else',1)
ename, expr = name_param(args, 'else', 1)
if ename != name:
raise ParseError, ('name in else does not match if', 'in')
elses=section.blocks
else: elses=None
raise ParseError('name in else does not match if', 'in')
elses = section.blocks
else:
elses = None
for tname, args, section in blocks[1:]:
if tname=='else':
raise ParseError, (
if tname == 'else':
raise ParseError(
'more than one else tag for a single if tag', 'in')
args=parse_params(args, name='', expr='')
name,expr=name_param(args,'elif',1)
if expr is None: cond=name
else: cond=expr.eval
args = parse_params(args, name='', expr='')
name, expr = name_param(args, 'elif', 1)
if expr is None:
cond = name
else:
cond = expr.eval
sections.append(cond)
sections.append(section.blocks)
if elses is not None: sections.append(elses)
if elses is not None:
sections.append(elses)
self.simple_form = ('i',) + tuple(sections)
self.simple_form=('i',)+tuple(sections)
class Unless:
name='unless'
blockContinuations=()
class Unless(object):
name = 'unless'
blockContinuations = ()
def __init__(self, blocks):
tname, args, section = blocks[0]
args=parse_params(args, name='', expr='')
name,expr=name_param(args,'unless',1)
if expr is None: cond=name
else: cond=expr.eval
self.simple_form=('i',cond,None,section.blocks)
args = parse_params(args, name='', expr='')
name, expr = name_param(args, 'unless', 1)
if expr is None:
cond = name
else:
cond = expr.eval
self.simple_form = ('i', cond, None, section.blocks)
class Else(Unless):
# The else tag is included for backward compatibility and is deprecated.
name='else'
name = 'else'
This diff is collapsed.
This diff is collapsed.
......@@ -43,12 +43,14 @@
import re
from DocumentTemplate.DT_Util import render_blocks, Eval, ParseError
from DocumentTemplate.DT_Util import str # Probably needed due to
# hysterical pickles.
# Probably needed due to hysterical pickles.
from DocumentTemplate.DT_Util import str # NOQA
class Let:
blockContinuations=()
name='let'
class Let(object):
blockContinuations = ()
name = 'let'
def __init__(self, blocks):
tname, args, section = blocks[0]
......@@ -57,55 +59,65 @@ class Let:
self.args = args = parse_let_params(args)
for i in range(len(args)):
name,expr = args[i]
if expr[:1]=='"' and expr[-1:]=='"' and len(expr) > 1:
# expr shorthand
expr=expr[1:-1]
try: args[i] = name, Eval(expr).eval
except SyntaxError, v:
m,(huh,l,c,src) = v
raise ParseError, (
name, expr = args[i]
if expr[:1] == '"' and expr[-1:] == '"' and len(expr) > 1:
# expr shorthand
expr = expr[1:-1]
try:
args[i] = name, Eval(expr).eval
except SyntaxError as v:
m, (huh, l, c, src) = v
raise ParseError(
'<strong>Expression (Python) Syntax error</strong>:'
'\n<pre>\n%s\n</pre>\n' % v[0],
'let')
def render(self, md):
d={}; md._push(d)
d = {}
md._push(d)
try:
for name,expr in self.args:
if type(expr) is type(''): d[name]=md[expr]
else: d[name]=expr(md)
for name, expr in self.args:
if isinstance(expr, str):
d[name] = md[expr]
else:
d[name] = expr(md)
return render_blocks(self.section, md)
finally: md._pop(1)
finally:
md._pop(1)
__call__ = render
def parse_let_params(text,
result=None,
tag='let',
parmre=re.compile('([\000- ]*([^\000- ="]+)=([^\000- ="]+))'),
qparmre=re.compile('([\000- ]*([^\000- ="]+)="([^"]*)")'),
**parms):
def parse_let_params(
text,
result=None,
tag='let',
parmre=re.compile('([\000- ]*([^\000- ="]+)=([^\000- ="]+))'),
qparmre=re.compile('([\000- ]*([^\000- ="]+)="([^"]*)")'),
**parms):
result=result or []
result = result or []
mo = parmre.match(text)
mo1= qparmre.match(text)
mo1 = qparmre.match(text)
if mo is not None:
name=mo.group(2)
value=mo.group(3)
l=len(mo.group(1))
name = mo.group(2)
value = mo.group(3)
l = len(mo.group(1))
elif mo1 is not None:
name=mo1.group(2)
value='"%s"' % mo1.group(3)
l=len(mo1.group(1))
name = mo1.group(2)
value = '"%s"' % mo1.group(3)
l = len(mo1.group(1))
else:
if not text or not text.strip(): return result
raise ParseError, ('invalid parameter: "%s"' % text, tag)
if not text or not text.strip():
return result
raise ParseError('invalid parameter: "%s"' % text, tag)
result.append((name,value))
result.append((name, value))
text=text[l:].strip()
if text: return parse_let_params(text,result,tag,**parms)
else: return result
text = text[l:].strip()
if text:
return parse_let_params(text, result, tag, **parms)
else:
return result
......@@ -23,8 +23,6 @@
<!--#/if-->
'''
__rcs_id__='$Id: DT_Raise.py 110402 2010-04-01 16:04:02Z tseaver $'
__version__='$Revision: 1.13 $'[11:-2]
from zExceptions import upgradeException
from zExceptions import convertExceptionType
......@@ -32,13 +30,16 @@ from DocumentTemplate.DT_Util import name_param
from DocumentTemplate.DT_Util import parse_params
from DocumentTemplate.DT_Util import render_blocks
class InvalidErrorTypeExpression(Exception):
pass
class Raise:
blockContinuations=()
name='raise'
expr=''
class Raise(object):
blockContinuations = ()
name = 'raise'
expr = ''
def __init__(self, blocks):
......@@ -47,7 +48,7 @@ class Raise:
args = parse_params(args, type='', expr='')
self.__name__, self.expr = name_param(args, 'raise', 1, attr='type')
def render(self,md):
def render(self, md):
expr = self.expr
if expr is None:
t = convertExceptionType(self.__name__)
......@@ -65,11 +66,11 @@ class Raise:
v = render_blocks(self.section, md)
except:
v = 'Invalid Error Value'
# String Exceptions are deprecated on Python 2.5 and
# plain won't work at all on Python 2.6. So try to upgrade it
# to a real exception.
t, v = upgradeException(t, v)
raise t, v
raise t(v)
__call__ = render
......@@ -10,13 +10,14 @@
# FOR A PARTICULAR PURPOSE
#
##############################################################################
__version__='$Revision: 1.9 $'[11:-2]
from DocumentTemplate.DT_Util import parse_params, name_param
class ReturnTag:
name='return'
expr=None
class ReturnTag(object):
name = 'return'
expr = None
def __init__(self, args):
args = parse_params(args, name='', expr='')
......@@ -34,6 +35,7 @@ class ReturnTag:
__call__ = render
class DTReturn:
class DTReturn(object):
def __init__(self, v):
self.v = v
This diff is collapsed.
......@@ -11,13 +11,16 @@
#
##############################################################################
import sys, traceback
import sys
import traceback
from cStringIO import StringIO
from DocumentTemplate.DT_Util import ParseError, parse_params, render_blocks
from DocumentTemplate.DT_Util import namespace, InstanceDict
from DocumentTemplate.DT_Return import DTReturn
class Try:
class Try(object):
"""Zope DTML Exception handling
usage:
......@@ -84,8 +87,8 @@ class Try:
name = 'try'
blockContinuations = 'except', 'else', 'finally'
finallyBlock=None
elseBlock=None
finallyBlock = None
elseBlock = None
def __init__(self, blocks):
tname, args, section = blocks[0]
......@@ -93,7 +96,6 @@ class Try:
self.args = parse_params(args)
self.section = section.blocks
# Find out if this is a try..finally type
if len(blocks) == 2 and blocks[1][0] == 'finally':
self.finallyBlock = blocks[1][2].blocks
......@@ -104,36 +106,36 @@ class Try:
self.handlers = []
defaultHandlerFound = 0
for tname,nargs,nsection in blocks[1:]:
for tname, nargs, nsection in blocks[1:]:
if tname == 'else':
if not self.elseBlock is None:
raise ParseError, (
if self.elseBlock is not None:
raise ParseError(
'No more than one else block is allowed',
self.name)
self.elseBlock = nsection.blocks
elif tname == 'finally':
raise ParseError, (
raise ParseError(
'A try..finally combination cannot contain '
'any other else, except or finally blocks',
self.name)
else:
if not self.elseBlock is None:
raise ParseError, (
if self.elseBlock is not None:
raise ParseError(
'The else block should be the last block '
'in a try tag', self.name)
for errname in nargs.split():
self.handlers.append((errname,nsection.blocks))
if nargs.strip()=='':
self.handlers.append((errname, nsection.blocks))
if nargs.strip() == '':
if defaultHandlerFound:
raise ParseError, (
raise ParseError(
'Only one default exception handler '
'is allowed', self.name)
else:
defaultHandlerFound = 1
self.handlers.append(('',nsection.blocks))
self.handlers.append(('', nsection.blocks))
def render(self, md):
if (self.finallyBlock is None):
......@@ -151,8 +153,8 @@ class Try:
raise
except:
# but an error occurs.. save the info.
t,v = sys.exc_info()[:2]
if type(t)==type(''):
t, v = sys.exc_info()[:2]
if isinstance(t, str):
errname = t
else:
errname = t.__name__
......@@ -165,12 +167,12 @@ class Try:
# found the handler block, now render it
try:
f=StringIO()
traceback.print_exc(100,f)
error_tb=f.getvalue()
f = StringIO()
traceback.print_exc(100, f)
error_tb = f.getvalue()
ns = namespace(md, error_type=errname, error_value=v,
error_tb=error_tb)[0]
md._push(InstanceDict(ns,md))
error_tb=error_tb)[0]
md._push(InstanceDict(ns, md))
return render_blocks(handler, md)
finally:
md._pop(1)
......@@ -192,22 +194,23 @@ class Try:
result = result + render_blocks(self.finallyBlock, md)
return result
def find_handler(self,exception):
def find_handler(self, exception):
"recursively search for a handler for a given exception"
if type(exception)==type(''):
for e,h in self.handlers:
if exception==e or e=='':
if isinstance(exception, str):
for e, h in self.handlers:
if exception == e or e == '':
return h
else:
return None
for e,h in self.handlers:
if e==exception.__name__ or e=='' or self.match_base(exception,e):
for e, h in self.handlers:
if (e == exception.__name__ or
e == '' or self.match_base(exception, e)):
return h
return None
def match_base(self,exception,name):
def match_base(self, exception, name):
for base in exception.__bases__:
if base.__name__==name or self.match_base(base,name):
if base.__name__ == name or self.match_base(base, name):
return 1
return None
......
......@@ -10,18 +10,16 @@
# FOR A PARTICULAR PURPOSE
#
##############################################################################
__doc__='''Machinery to support through-the-web editing
$Id: DT_UI.py 110402 2010-04-01 16:04:02Z tseaver $'''
__version__='$Revision: 1.15 $'[11:-2]
'''Machinery to support through-the-web editing
'''
from DocumentTemplate.DT_HTML import HTML
FactoryDefaultString="Factory Default"
FactoryDefaultString = "Factory Default"
HTML.document_template_edit_header='<h2>Edit Document</h2>'
HTML.document_template_form_header=''
HTML.document_template_edit_footer=(
HTML.document_template_edit_header = '<h2>Edit Document</h2>'
HTML.document_template_form_header = ''
HTML.document_template_edit_footer = (
"""<FONT SIZE="-1">
<I><A HREF="http://www.zope.com">
&copy; 2002 Zope Corporation</A></I></FONT>""")
......@@ -75,7 +73,7 @@ HTML._manage_editForm = HTML(
</BODY>
</HTML>""",)
HTML.editConfirmation=HTML(
HTML.editConfirmation = HTML(
"""<html><head><title>Change Successful</title></head><body>
<!--#if CANCEL_ACTION-->
<form action="&dtml-CANCEL_ACTION;" method="POST">
......
This diff is collapsed.
This diff is collapsed.
......@@ -33,49 +33,56 @@
'''
__rcs_id__='$Id: DT_With.py 110402 2010-04-01 16:04:02Z tseaver $'
__version__='$Revision: 1.15 $'[11:-2]
from DocumentTemplate.DT_Util import parse_params, name_param
from DocumentTemplate.DT_Util import InstanceDict, render_blocks, str
from DocumentTemplate.DT_Util import InstanceDict, render_blocks, str # NOQA
from DocumentTemplate.DT_Util import TemplateDict
class With:
blockContinuations=()
name='with'
mapping=None
only=0
class With(object):
blockContinuations = ()
name = 'with'
mapping = None
only = 0
def __init__(self, blocks):
tname, args, section = blocks[0]
args=parse_params(args, name='', expr='', mapping=1, only=1)
name,expr=name_param(args,'with',1)
if expr is None: expr=name
else: expr=expr.eval
args = parse_params(args, name='', expr='', mapping=1, only=1)
name, expr = name_param(args, 'with', 1)
if expr is None:
expr = name
else:
expr = expr.eval
self.__name__, self.expr = name, expr
self.section=section.blocks
if args.has_key('mapping') and args['mapping']: self.mapping=1
if args.has_key('only') and args['only']: self.only=1
self.section = section.blocks
if 'mapping' in args and args['mapping']:
self.mapping = 1
if 'only' in args and args['only']:
self.only = 1
def render(self, md):
expr=self.expr
if type(expr) is type(''): v=md[expr]
else: v=expr(md)
expr = self.expr
if isinstance(expr, str):
v = md[expr]
else:
v = expr(md)
if not self.mapping:
if type(v) is type(()) and len(v)==1: v=v[0]
v=InstanceDict(v,md)
if isinstance(v, tuple) and len(v) == 1:
v = v[0]
v = InstanceDict(v, md)
if self.only:
_md=md
md=TemplateDict()
_md = md
md = TemplateDict()
if hasattr(_md, 'guarded_getattr'):
md.guarded_getattr = _md.guarded_getattr
if hasattr(_md, 'guarded_getitem'):
md.guarded_getitem = _md.guarded_getitem
md._push(v)
try: return render_blocks(self.section, md)
finally: md._pop(1)
try:
return render_blocks(self.section, md)
finally:
md._pop(1)
__call__=render
__call__ = render
This diff is collapsed.
The let tag:
is a new tag that lets you create blocks like:
<!--#in "1,2,3,4"-->
<!--#let num=sequence-item
index=sequence-index
result="num*index"-->
<!--#var num--> * <!--#var index--> = <!--#var result-->
<!--#/let-->
<!--#/in-->
Which yields:
1 * 0 = 0
2 * 1 = 2
3 * 2 = 6
4 * 3 = 12
The #let tag works like the #with tag, but is more flexible in that
it allows you to make multiple assignments, and allows you to chain
assignments, using earlier declarations in later assignments. Notice
inthe ablove example, the 'result' variable is based on 'num' and
'index', both of which are assigned in the same #let expression.
Syntacticly, each argument to be evalulated in the head of the let
tag must be seperated by a newline. Enclosing an argument in double
quotes causes it to be evaluated by the DTML expression machinery.
Un-quoted arguments are referenced by name.
Evaluation is in sequence with the result of earlier assignments
available to later ones. Later assignments can also override earlier
ones, which can be helpful for longer step-by-step calculations. The
variables thus set are in effect for the life of the <!--#let-->
block.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment