Commit a5ab9f75 authored by Andreas Jung's avatar Andreas Jung

replace string module calls by string methods

parent 19586474
...@@ -17,12 +17,11 @@ Page Template-specific implementation of TALES, with handlers ...@@ -17,12 +17,11 @@ Page Template-specific implementation of TALES, with handlers
for Python expressions, string literals, and paths. for Python expressions, string literals, and paths.
""" """
__version__='$Revision: 1.34 $'[11:-2] __version__='$Revision: 1.35 $'[11:-2]
import re, sys import re, sys
from TALES import Engine, CompilerError, _valid_name, NAME_RE, \ from TALES import Engine, CompilerError, _valid_name, NAME_RE, \
Undefined, Default, _parse_expr Undefined, Default, _parse_expr
from string import strip, split, join, replace, lstrip
from Acquisition import aq_base, aq_inner, aq_parent from Acquisition import aq_base, aq_inner, aq_parent
...@@ -104,7 +103,7 @@ def render(ob, ns): ...@@ -104,7 +103,7 @@ def render(ob, ns):
class SubPathExpr: class SubPathExpr:
def __init__(self, path): def __init__(self, path):
self._path = path = split(strip(path), '/') self._path = path = path.strip().split('/')
self._base = base = path.pop(0) self._base = base = path.pop(0)
if not _valid_name(base): if not _valid_name(base):
raise CompilerError, 'Invalid variable name "%s"' % base raise CompilerError, 'Invalid variable name "%s"' % base
...@@ -145,15 +144,15 @@ class PathExpr: ...@@ -145,15 +144,15 @@ class PathExpr:
def __init__(self, name, expr, engine): def __init__(self, name, expr, engine):
self._s = expr self._s = expr
self._name = name self._name = name
paths = split(expr, '|') paths = expr.split('|')
self._subexprs = [] self._subexprs = []
add = self._subexprs.append add = self._subexprs.append
for i in range(len(paths)): for i in range(len(paths)):
path = lstrip(paths[i]) path = paths[i].lstrip()
if _parse_expr(path): if _parse_expr(path):
# This part is the start of another expression type, # This part is the start of another expression type,
# so glue it back together and compile it. # so glue it back together and compile it.
add(engine.compile(lstrip(join(paths[i:], '|')))) add(engine.compile(('|'.join(paths[i:]).lstrip())))
break break
add(SubPathExpr(path)._eval) add(SubPathExpr(path)._eval)
...@@ -204,11 +203,11 @@ class StringExpr: ...@@ -204,11 +203,11 @@ class StringExpr:
def __init__(self, name, expr, engine): def __init__(self, name, expr, engine):
self._s = expr self._s = expr
if '%' in expr: if '%' in expr:
expr = replace(expr, '%', '%%') expr = expr.replace('%', '%%')
self._vars = vars = [] self._vars = vars = []
if '$' in expr: if '$' in expr:
parts = [] parts = []
for exp in split(expr, '$$'): for exp in expr.split('$$'):
if parts: parts.append('$') if parts: parts.append('$')
m = _interp.search(exp) m = _interp.search(exp)
while m is not None: while m is not None:
...@@ -222,7 +221,7 @@ class StringExpr: ...@@ -222,7 +221,7 @@ class StringExpr:
raise CompilerError, ( raise CompilerError, (
'$ must be doubled or followed by a simple path') '$ must be doubled or followed by a simple path')
parts.append(exp) parts.append(exp)
expr = join(parts, '') expr = ''.join(parts)
self._expr = expr self._expr = expr
def __call__(self, econtext): def __call__(self, econtext):
...@@ -243,7 +242,7 @@ class StringExpr: ...@@ -243,7 +242,7 @@ class StringExpr:
class NotExpr: class NotExpr:
def __init__(self, name, expr, compiler): def __init__(self, name, expr, compiler):
self._s = expr = lstrip(expr) self._s = expr = expr.lstrip()
self._c = compiler.compile(expr) self._c = compiler.compile(expr)
def __call__(self, econtext): def __call__(self, econtext):
...@@ -265,7 +264,7 @@ class DeferWrapper: ...@@ -265,7 +264,7 @@ class DeferWrapper:
class DeferExpr: class DeferExpr:
def __init__(self, name, expr, compiler): def __init__(self, name, expr, compiler):
self._s = expr = lstrip(expr) self._s = expr = expr.lstrip()
self._c = compiler.compile(expr) self._c = compiler.compile(expr)
def __call__(self, econtext): def __call__(self, econtext):
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
HTML- and XML-based template objects using TAL, TALES, and METAL. HTML- and XML-based template objects using TAL, TALES, and METAL.
""" """
__version__='$Revision: 1.23 $'[11:-2] __version__='$Revision: 1.24 $'[11:-2]
import sys import sys
...@@ -24,7 +24,6 @@ from TAL.HTMLTALParser import HTMLTALParser ...@@ -24,7 +24,6 @@ from TAL.HTMLTALParser import HTMLTALParser
from TAL.TALGenerator import TALGenerator from TAL.TALGenerator import TALGenerator
from TAL.TALInterpreter import TALInterpreter from TAL.TALInterpreter import TALInterpreter
from Expressions import getEngine from Expressions import getEngine
from string import join, strip, rstrip, split, replace, lower, find
from cStringIO import StringIO from cStringIO import StringIO
from ExtensionClass import Base from ExtensionClass import Base
from ComputedAttribute import ComputedAttribute from ComputedAttribute import ComputedAttribute
...@@ -148,7 +147,7 @@ class PageTemplate(Base): ...@@ -148,7 +147,7 @@ class PageTemplate(Base):
self._text) ) self._text) )
return ('%s\n %s\n-->\n%s' % (self._error_start, return ('%s\n %s\n-->\n%s' % (self._error_start,
join(self._v_errors, '\n '), '\n '.join(self._v_errors),
self._text)) self._text))
def _cook(self): def _cook(self):
...@@ -182,7 +181,7 @@ class PageTemplate(Base): ...@@ -182,7 +181,7 @@ class PageTemplate(Base):
class _ModuleImporter: class _ModuleImporter:
def __getitem__(self, module): def __getitem__(self, module):
mod = __import__(module) mod = __import__(module)
path = split(module, '.') path = module.split('.')
for name in path[1:]: for name in path[1:]:
mod = getattr(mod, name) mod = getattr(mod, name)
return mod return mod
......
...@@ -15,12 +15,11 @@ ...@@ -15,12 +15,11 @@
Zope object encapsulating a Page Template from the filesystem. Zope object encapsulating a Page Template from the filesystem.
""" """
__version__='$Revision: 1.13 $'[11:-2] __version__='$Revision: 1.14 $'[11:-2]
import os, AccessControl, Acquisition, sys import os, AccessControl, Acquisition, sys
from Globals import package_home, DevelopmentMode from Globals import package_home, DevelopmentMode
from zLOG import LOG, ERROR, INFO from zLOG import LOG, ERROR, INFO
from string import join, strip, rstrip, split, lower
from Shared.DC.Scripts.Script import Script, BindingsUI from Shared.DC.Scripts.Script import Script, BindingsUI
from Shared.DC.Scripts.Signature import FuncCode from Shared.DC.Scripts.Signature import FuncCode
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
...@@ -116,7 +115,7 @@ class PageTemplateFile(Script, PageTemplate, Traversable): ...@@ -116,7 +115,7 @@ class PageTemplateFile(Script, PageTemplate, Traversable):
self._cook() self._cook()
if self._v_errors: if self._v_errors:
LOG('PageTemplateFile', ERROR, 'Error in template', LOG('PageTemplateFile', ERROR, 'Error in template',
join(self._v_errors, '\n')) '\n'.join(self._v_errors))
return return
self._v_last_read = mtime self._v_last_read = mtime
......
...@@ -17,11 +17,10 @@ A TALES Iterator with the ability to use first() and last() on ...@@ -17,11 +17,10 @@ A TALES Iterator with the ability to use first() and last() on
subpaths of elements. subpaths of elements.
""" """
__version__='$Revision: 1.2 $'[11:-2] __version__='$Revision: 1.3 $'[11:-2]
import TALES import TALES
from Expressions import restrictedTraverse, Undefs, getSecurityManager from Expressions import restrictedTraverse, Undefs, getSecurityManager
from string import split
class Iterator(TALES.Iterator): class Iterator(TALES.Iterator):
def __bobo_traverse__(self, REQUEST, name): def __bobo_traverse__(self, REQUEST, name):
...@@ -36,7 +35,7 @@ class Iterator(TALES.Iterator): ...@@ -36,7 +35,7 @@ class Iterator(TALES.Iterator):
if name is None: if name is None:
return ob1 == ob2 return ob1 == ob2
if isinstance(name, type('')): if isinstance(name, type('')):
name = split(name, '/') name = name.split('/')
name = filter(None, name) name = filter(None, name)
securityManager = getSecurityManager() securityManager = getSecurityManager()
try: try:
......
...@@ -14,10 +14,9 @@ ...@@ -14,10 +14,9 @@
"""Generic Python Expression Handler """Generic Python Expression Handler
""" """
__version__='$Revision: 1.6 $'[11:-2] __version__='$Revision: 1.7 $'[11:-2]
from TALES import CompilerError from TALES import CompilerError
from string import strip, split, join, replace, lstrip
from sys import exc_info from sys import exc_info
class getSecurityManager: class getSecurityManager:
...@@ -28,10 +27,10 @@ class getSecurityManager: ...@@ -28,10 +27,10 @@ class getSecurityManager:
class PythonExpr: class PythonExpr:
def __init__(self, name, expr, engine): def __init__(self, name, expr, engine):
self.expr = expr = replace(strip(expr), '\n', ' ') self.expr = expr = expr.strip().replace('\n', ' ')
try: try:
d = {} d = {}
exec 'def f():\n return %s\n' % strip(expr) in d exec 'def f():\n return %s\n' % expr.strip() in d
self._f = d['f'] self._f = d['f']
except: except:
raise CompilerError, ('Python expression error:\n' raise CompilerError, ('Python expression error:\n'
......
...@@ -17,23 +17,22 @@ Handler for Python expressions, using the pre-Python 2.1 restriction ...@@ -17,23 +17,22 @@ Handler for Python expressions, using the pre-Python 2.1 restriction
machinery from PythonScripts. machinery from PythonScripts.
""" """
__version__='$Revision: 1.6 $'[11:-2] __version__='$Revision: 1.7 $'[11:-2]
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
from Products.PythonScripts.Guarded import _marker, \ from Products.PythonScripts.Guarded import _marker, \
GuardedBlock, theGuard, safebin, WriteGuard, ReadGuard, UntupleFunction GuardedBlock, theGuard, safebin, WriteGuard, ReadGuard, UntupleFunction
from TALES import CompilerError from TALES import CompilerError
from string import strip, split, join, replace, lstrip
from PythonExpr import PythonExpr from PythonExpr import PythonExpr
class PythonExpr(PythonExpr): class PythonExpr(PythonExpr):
def __init__(self, name, expr, engine): def __init__(self, name, expr, engine):
self.expr = expr = replace(strip(expr), '\n', ' ') self.expr = expr = expr.strip().replace('\n', ' ')
blk = GuardedBlock('def f():\n return \\\n %s\n' % expr) blk = GuardedBlock('def f():\n return \\\n %s\n' % expr)
if blk.errors: if blk.errors:
raise CompilerError, ('Python expression error:\n%s' % raise CompilerError, ('Python expression error:\n%s' %
join(blk.errors, '\n') ) '\n'.join(blk.errors) )
guards = {'$guard': theGuard, '$write_guard': WriteGuard, guards = {'$guard': theGuard, '$write_guard': WriteGuard,
'$read_guard': ReadGuard, '__debug__': __debug__} '$read_guard': ReadGuard, '__debug__': __debug__}
self._f = UntupleFunction(blk.t, guards, __builtins__=safebin) self._f = UntupleFunction(blk.t, guards, __builtins__=safebin)
...@@ -43,7 +42,7 @@ class _SecureModuleImporter: ...@@ -43,7 +42,7 @@ class _SecureModuleImporter:
__allow_access_to_unprotected_subobjects__ = 1 __allow_access_to_unprotected_subobjects__ = 1
def __getitem__(self, module): def __getitem__(self, module):
mod = safebin['__import__'](module) mod = safebin['__import__'](module)
path = split(module, '.') path = module.split('.')
for name in path[1:]: for name in path[1:]:
mod = getattr(mod, name) mod = getattr(mod, name)
return mod return mod
......
...@@ -16,14 +16,13 @@ ...@@ -16,14 +16,13 @@
Handler for Python expressions that uses the RestrictedPython package. Handler for Python expressions that uses the RestrictedPython package.
""" """
__version__='$Revision: 1.8 $'[11:-2] __version__='$Revision: 1.9 $'[11:-2]
from AccessControl import full_read_guard, full_write_guard, \ from AccessControl import full_read_guard, full_write_guard, \
safe_builtins, getSecurityManager safe_builtins, getSecurityManager
from AccessControl.ZopeGuards import guarded_getattr, guarded_getitem from AccessControl.ZopeGuards import guarded_getattr, guarded_getitem
from RestrictedPython import compile_restricted_eval from RestrictedPython import compile_restricted_eval
from TALES import CompilerError from TALES import CompilerError
from string import strip, split, join, replace, lstrip
from PythonExpr import PythonExpr from PythonExpr import PythonExpr
...@@ -33,11 +32,11 @@ class PythonExpr(PythonExpr): ...@@ -33,11 +32,11 @@ class PythonExpr(PythonExpr):
'_getattr_': guarded_getattr, '_getattr_': guarded_getattr,
'_getitem_': guarded_getitem,} '_getitem_': guarded_getitem,}
def __init__(self, name, expr, engine): def __init__(self, name, expr, engine):
self.expr = expr = replace(strip(expr), '\n', ' ') self.expr = expr = expr.strip().replace('\n', ' ')
code, err, warn, use = compile_restricted_eval(expr, str(self)) code, err, warn, use = compile_restricted_eval(expr, str(self))
if err: if err:
raise CompilerError, ('Python expression error:\n%s' % raise CompilerError, ('Python expression error:\n%s' %
join(err, '\n') ) '\n'.join(err) )
self._f_varnames = use.keys() self._f_varnames = use.keys()
self._code = code self._code = code
...@@ -52,7 +51,7 @@ class _SecureModuleImporter: ...@@ -52,7 +51,7 @@ class _SecureModuleImporter:
__allow_access_to_unprotected_subobjects__ = 1 __allow_access_to_unprotected_subobjects__ = 1
def __getitem__(self, module): def __getitem__(self, module):
mod = safe_builtins['__import__'](module) mod = safe_builtins['__import__'](module)
path = split(module, '.') path = module.split('.')
for name in path[1:]: for name in path[1:]:
mod = getattr(mod, name) mod = getattr(mod, name)
return mod return mod
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
Zope object encapsulating a Page Template. Zope object encapsulating a Page Template.
""" """
__version__='$Revision: 1.37 $'[11:-2] __version__='$Revision: 1.38 $'[11:-2]
import os, AccessControl, Acquisition, sys import os, AccessControl, Acquisition, sys
from types import StringType from types import StringType
...@@ -23,7 +23,6 @@ from Globals import DTMLFile, ImageFile, MessageDialog, package_home ...@@ -23,7 +23,6 @@ from Globals import DTMLFile, ImageFile, MessageDialog, package_home
from zLOG import LOG, ERROR, INFO from zLOG import LOG, ERROR, INFO
from OFS.SimpleItem import SimpleItem from OFS.SimpleItem import SimpleItem
from DateTime.DateTime import DateTime from DateTime.DateTime import DateTime
from string import join, strip, rstrip, split, replace, lower
from Shared.DC.Scripts.Script import Script, BindingsUI from Shared.DC.Scripts.Script import Script, BindingsUI
from Shared.DC.Scripts.Signature import FuncCode from Shared.DC.Scripts.Signature import FuncCode
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
...@@ -119,7 +118,7 @@ class ZopePageTemplate(Script, PageTemplate, Historical, Cacheable, ...@@ -119,7 +118,7 @@ class ZopePageTemplate(Script, PageTemplate, Historical, Cacheable,
message = "Saved changes." message = "Saved changes."
if getattr(self, '_v_warnings', None): if getattr(self, '_v_warnings', None):
message = ("<strong>Warning:</strong> <i>%s</i>" message = ("<strong>Warning:</strong> <i>%s</i>"
% join(self._v_warnings, '<br>')) % '<br>'.join(self._v_warnings))
return self.pt_editForm(manage_tabs_message=message) return self.pt_editForm(manage_tabs_message=message)
def pt_setTitle(self, title): def pt_setTitle(self, title):
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
import markupbase import markupbase
import re import re
import string
# Regular expressions used for parsing # Regular expressions used for parsing
...@@ -258,7 +257,7 @@ class HTMLParser(markupbase.ParserBase): ...@@ -258,7 +257,7 @@ class HTMLParser(markupbase.ParserBase):
match = tagfind.match(rawdata, i+1) match = tagfind.match(rawdata, i+1)
assert match, 'unexpected call to parse_starttag()' assert match, 'unexpected call to parse_starttag()'
k = match.end() k = match.end()
self.lasttag = tag = string.lower(rawdata[i+1:k]) self.lasttag = tag = rawdata[i+1:k].lower()
while k < endpos: while k < endpos:
m = attrfind.match(rawdata, k) m = attrfind.match(rawdata, k)
...@@ -271,16 +270,16 @@ class HTMLParser(markupbase.ParserBase): ...@@ -271,16 +270,16 @@ class HTMLParser(markupbase.ParserBase):
attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue[:1] == '"' == attrvalue[-1:]:
attrvalue = attrvalue[1:-1] attrvalue = attrvalue[1:-1]
attrvalue = self.unescape(attrvalue) attrvalue = self.unescape(attrvalue)
attrs.append((string.lower(attrname), attrvalue)) attrs.append((attrname.lower(), attrvalue))
k = m.end() k = m.end()
end = string.strip(rawdata[k:endpos]) end = rawdata[k:endpos].strip()
if end not in (">", "/>"): if end not in (">", "/>"):
lineno, offset = self.getpos() lineno, offset = self.getpos()
if "\n" in self.__starttag_text: if "\n" in self.__starttag_text:
lineno = lineno + string.count(self.__starttag_text, "\n") lineno = lineno + self.__starttag_text.count("\n")
offset = len(self.__starttag_text) \ offset = len(self.__starttag_text) \
- string.rfind(self.__starttag_text, "\n") - self.__starttag_text.rfind("\n")
else: else:
offset = offset + len(self.__starttag_text) offset = offset + len(self.__starttag_text)
self.error("junk characters in start tag: %s" self.error("junk characters in start tag: %s"
...@@ -338,7 +337,7 @@ class HTMLParser(markupbase.ParserBase): ...@@ -338,7 +337,7 @@ class HTMLParser(markupbase.ParserBase):
if not match: if not match:
self.error("bad end tag: %s" % `rawdata[i:j]`) self.error("bad end tag: %s" % `rawdata[i:j]`)
tag = match.group(1) tag = match.group(1)
self.handle_endtag(string.lower(tag)) self.handle_endtag(tag.lower())
return j return j
# Overridable -- finish processing of start+end tag: <tag.../> # Overridable -- finish processing of start+end tag: <tag.../>
...@@ -385,9 +384,9 @@ class HTMLParser(markupbase.ParserBase): ...@@ -385,9 +384,9 @@ class HTMLParser(markupbase.ParserBase):
def unescape(self, s): def unescape(self, s):
if '&' not in s: if '&' not in s:
return s return s
s = string.replace(s, "&lt;", "<") s = s.replace("&lt;", "<")
s = string.replace(s, "&gt;", ">") s = s.replace("&gt;", ">")
s = string.replace(s, "&apos;", "'") s = s.replace("&apos;", "'")
s = string.replace(s, "&quot;", '"') s = s.replace("&quot;", '"')
s = string.replace(s, "&amp;", "&") # Must be last s = s.replace("&amp;", "&") # Must be last
return s return s
"""Shared support for scanning document type declarations in HTML and XHTML.""" """Shared support for scanning document type declarations in HTML and XHTML."""
import re import re, string
import string
_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9]*\s*').match _declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9]*\s*').match
_declstringlit_match = re.compile(r'(\'[^\']*\'|"[^"]*")\s*').match _declstringlit_match = re.compile(r'(\'[^\']*\'|"[^"]*")\s*').match
...@@ -29,10 +28,10 @@ class ParserBase: ...@@ -29,10 +28,10 @@ class ParserBase:
if i >= j: if i >= j:
return j return j
rawdata = self.rawdata rawdata = self.rawdata
nlines = string.count(rawdata, "\n", i, j) nlines = rawdata.count("\n", i, j)
if nlines: if nlines:
self.lineno = self.lineno + nlines self.lineno = self.lineno + nlines
pos = string.rindex(rawdata, "\n", i, j) # Should not fail pos = rawdata.rindex("\n", i, j) # Should not fail
self.offset = j-(pos+1) self.offset = j-(pos+1)
else: else:
self.offset = self.offset + j-i self.offset = self.offset + j-i
...@@ -169,7 +168,7 @@ class ParserBase: ...@@ -169,7 +168,7 @@ class ParserBase:
return -1 return -1
# style content model; just skip until '>' # style content model; just skip until '>'
if '>' in rawdata[j:]: if '>' in rawdata[j:]:
return string.find(rawdata, ">", j) + 1 return rawdata.find(">", j) + 1
return -1 return -1
# Internal -- scan past <!ATTLIST declarations # Internal -- scan past <!ATTLIST declarations
...@@ -193,7 +192,7 @@ class ParserBase: ...@@ -193,7 +192,7 @@ class ParserBase:
if c == "(": if c == "(":
# an enumerated type; look for ')' # an enumerated type; look for ')'
if ")" in rawdata[j:]: if ")" in rawdata[j:]:
j = string.find(rawdata, ")", j) + 1 j = awdata.find(")", j) + 1
else: else:
return -1 return -1
while rawdata[j:j+1] in string.whitespace: while rawdata[j:j+1] in string.whitespace:
...@@ -300,7 +299,7 @@ class ParserBase: ...@@ -300,7 +299,7 @@ class ParserBase:
name = s.strip() name = s.strip()
if (i + len(s)) == n: if (i + len(s)) == n:
return None, -1 # end of buffer return None, -1 # end of buffer
return string.lower(name), m.end() return name.lower(), m.end()
else: else:
self.updatepos(declstartpos, i) self.updatepos(declstartpos, i)
self.error("expected name token", self.getpos()) self.error("expected name token", self.getpos())
...@@ -21,7 +21,7 @@ else: ...@@ -21,7 +21,7 @@ else:
for line in f.readlines(): for line in f.readlines():
line = line.strip() line = line.strip()
if line and line[0] != '#': if line and line[0] != '#':
for dir in string.split(line, os.pathsep): for dir in line.split(os.pathsep):
dir = os.path.expanduser(os.path.expandvars(dir)) dir = os.path.expanduser(os.path.expandvars(dir))
if dir not in sys.path: if dir not in sys.path:
sys.path.append(dir) sys.path.append(dir)
......
...@@ -18,10 +18,8 @@ The Iterator() function accepts either a sequence or a Python ...@@ -18,10 +18,8 @@ The Iterator() function accepts either a sequence or a Python
iterator. The next() method fetches the next item, and returns iterator. The next() method fetches the next item, and returns
true if it succeeds. true if it succeeds.
$Id: Iterator.py,v 1.5 2001/12/13 18:35:32 evan Exp $''' $Id: Iterator.py,v 1.6 2002/04/19 14:16:08 andreasjung Exp $'''
__version__='$Revision: 1.5 $'[11:-2] __version__='$Revision: 1.6 $'[11:-2]
import string
class Iterator: class Iterator:
'''Simple Iterator class''' '''Simple Iterator class'''
...@@ -88,8 +86,8 @@ class Iterator: ...@@ -88,8 +86,8 @@ class Iterator:
s = s + r * rct s = s + r * rct
return s return s
def roman(self, lower=string.lower): def roman(self):
return lower(self.Roman()) return self.Roman().lower()
def first(self, name=None): def first(self, name=None):
if self.start: return 1 if self.start: return 1
......
...@@ -12,8 +12,8 @@ ...@@ -12,8 +12,8 @@
############################################################################## ##############################################################################
__doc__='''Tree manipulation classes __doc__='''Tree manipulation classes
$Id: Tree.py,v 1.4 2001/11/28 15:51:22 matt Exp $''' $Id: Tree.py,v 1.5 2002/04/19 14:16:08 andreasjung Exp $'''
__version__='$Revision: 1.4 $'[11:-2] __version__='$Revision: 1.5 $'[11:-2]
from Acquisition import Explicit from Acquisition import Explicit
from ComputedAttribute import ComputedAttribute from ComputedAttribute import ComputedAttribute
...@@ -147,11 +147,10 @@ def aqcallback(self, inst, parent, name, value, filter): ...@@ -147,11 +147,10 @@ def aqcallback(self, inst, parent, name, value, filter):
return filter(self, inst, parent, name, value) return filter(self, inst, parent, name, value)
from binascii import b2a_base64, a2b_base64 from binascii import b2a_base64, a2b_base64
import string from string import translate, maketrans
from string import split, join, translate
a2u_map = string.maketrans('+/=', '-._') a2u_map = maketrans('+/=', '-._')
u2a_map = string.maketrans('-._', '+/=') u2a_map = maketrans('-._', '+/=')
def b2a(s): def b2a(s):
'''Encode a value as a cookie- and url-safe string. '''Encode a value as a cookie- and url-safe string.
...@@ -164,7 +163,7 @@ def b2a(s): ...@@ -164,7 +163,7 @@ def b2a(s):
frags = [] frags = []
for i in range(0, len(s), 57): for i in range(0, len(s), 57):
frags.append(b2a_base64(s[i:i + 57])[:-1]) frags.append(b2a_base64(s[i:i + 57])[:-1])
return translate(join(frags, ''), a2u_map) return translate(''.join(frags), a2u_map)
def a2b(s): def a2b(s):
'''Decode a b2a-encoded string.''' '''Decode a b2a-encoded string.'''
...@@ -174,7 +173,7 @@ def a2b(s): ...@@ -174,7 +173,7 @@ def a2b(s):
frags = [] frags = []
for i in range(0, len(s), 76): for i in range(0, len(s), 76):
frags.append(a2b_base64(s[i:i + 76])) frags.append(a2b_base64(s[i:i + 76]))
return join(frags, '') return ''.join(frags)
def encodeExpansion(nodes): def encodeExpansion(nodes):
'''Encode the expanded node ids of a tree into a string. '''Encode the expanded node ids of a tree into a string.
...@@ -196,7 +195,7 @@ def encodeExpansion(nodes): ...@@ -196,7 +195,7 @@ def encodeExpansion(nodes):
steps.append(node.id) steps.append(node.id)
node.expansion_number = n node.expansion_number = n
n = n + 1 n = n + 1
return join(steps, ':') return ':'.join(steps)
def decodeExpansion(s, nth=None): def decodeExpansion(s, nth=None):
'''Decode an expanded node map from a string. '''Decode an expanded node map from a string.
...@@ -209,7 +208,7 @@ def decodeExpansion(s, nth=None): ...@@ -209,7 +208,7 @@ def decodeExpansion(s, nth=None):
nth_pair = None nth_pair = None
if nth is not None: if nth is not None:
nth_pair = (None, None) nth_pair = (None, None)
for step in split(s, ':'): for step in s.split(':'):
if step[:1] == '.': if step[:1] == '.':
pop = len(step) - 1 pop = len(step) - 1
continue continue
......
...@@ -12,8 +12,8 @@ ...@@ -12,8 +12,8 @@
############################################################################## ##############################################################################
__doc__='''Zope-specific versions of ZTUTils classes __doc__='''Zope-specific versions of ZTUTils classes
$Id: Zope.py,v 1.8 2002/02/15 16:26:56 evan Exp $''' $Id: Zope.py,v 1.9 2002/04/19 14:16:08 andreasjung Exp $'''
__version__='$Revision: 1.8 $'[11:-2] __version__='$Revision: 1.9 $'[11:-2]
import sys, cgi, urllib, cgi import sys, cgi, urllib, cgi
from Tree import encodeExpansion, decodeExpansion, TreeMaker from Tree import encodeExpansion, decodeExpansion, TreeMaker
...@@ -21,7 +21,6 @@ from SimpleTree import SimpleTreeMaker ...@@ -21,7 +21,6 @@ from SimpleTree import SimpleTreeMaker
from Batch import Batch from Batch import Batch
from Products.ZCatalog.Lazy import Lazy from Products.ZCatalog.Lazy import Lazy
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
from string import split, join
from types import StringType, ListType, IntType, FloatType from types import StringType, ListType, IntType, FloatType
from DateTime import DateTime from DateTime import DateTime
...@@ -117,7 +116,7 @@ class SimpleTreeMaker(TreeSkipMixin, SimpleTreeMaker): ...@@ -117,7 +116,7 @@ class SimpleTreeMaker(TreeSkipMixin, SimpleTreeMaker):
if state: if state:
setst = req.form.get(set_name) setst = req.form.get(set_name)
if setst: if setst:
st, pn, expid = split(setst, ',') st, pn, expid = setst.split(',')
state, (m, obid) = decodeExpansion(state, int(pn)) state, (m, obid) = decodeExpansion(state, int(pn))
if m is None: if m is None:
pass pass
...@@ -178,7 +177,7 @@ def make_query(*args, **kwargs): ...@@ -178,7 +177,7 @@ def make_query(*args, **kwargs):
k, m, v = qlist[i] k, m, v = qlist[i]
qlist[i] = '%s%s=%s' % (uq(k), m, uq(str(v))) qlist[i] = '%s%s=%s' % (uq(k), m, uq(str(v)))
return join(qlist, '&') return '&'.join(qlist)
def make_hidden_input(*args, **kwargs): def make_hidden_input(*args, **kwargs):
'''Construct a set of hidden input elements, with marshalling markup. '''Construct a set of hidden input elements, with marshalling markup.
...@@ -205,7 +204,7 @@ def make_hidden_input(*args, **kwargs): ...@@ -205,7 +204,7 @@ def make_hidden_input(*args, **kwargs):
qlist[i] = ('<input type="hidden" name="%s%s" value="%s">' qlist[i] = ('<input type="hidden" name="%s%s" value="%s">'
% (hq(k), m, hq(str(v)))) % (hq(k), m, hq(str(v))))
return join(qlist, '\n') return '\n'.join(qlist)
def complex_marshal(pairs): def complex_marshal(pairs):
'''Add request marshalling information to a list of name-value pairs. '''Add request marshalling information to a list of name-value pairs.
...@@ -274,7 +273,7 @@ def url_query(request, req_name="URL", omit=None): ...@@ -274,7 +273,7 @@ def url_query(request, req_name="URL", omit=None):
qs = request.get('QUERY_STRING', '') qs = request.get('QUERY_STRING', '')
if qs and omit: if qs and omit:
qsparts = split(qs, '&') qsparts = qs.split('&')
if isinstance(omit, StringType): if isinstance(omit, StringType):
omits = {omit: None} omits = {omit: None}
...@@ -286,17 +285,17 @@ def url_query(request, req_name="URL", omit=None): ...@@ -286,17 +285,17 @@ def url_query(request, req_name="URL", omit=None):
unq = urllib.unquote unq = urllib.unquote
for i in range(len(qsparts)): for i in range(len(qsparts)):
name = unq(split(qsparts[i], '=', 1)[0]) name = unq(qsparts[i].split('=', 1)[0])
if omitted(name): if omitted(name):
qsparts[i] = '' qsparts[i] = ''
name = split(name, ':', 1)[0] name = name.split(':', 1)[0]
if omitted(name): if omitted(name):
qsparts[i] = '' qsparts[i] = ''
name = split(name, '.', 1)[0] name = name.split('.', 1)[0]
if omitted(name): if omitted(name):
qsparts[i] = '' qsparts[i] = ''
qs = join(filter(None, qsparts), '&') qs = '&'.join(filter(None, qsparts))
# We alway append '?' since arguments will be appended to the URL # We alway append '?' since arguments will be appended to the URL
return '%s?%s' % (base, qs) return '%s?%s' % (base, qs)
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