Commit 2639fcb7 authored by Martijn Pieters's avatar Martijn Pieters

Clean up indentation and trailing whitespace.

parent bdb3057e
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""HTML formated DocumentTemplates
$Id: DT_HTML.py,v 1.31 2001/11/28 15:50:54 matt Exp $"""
$Id: DT_HTML.py,v 1.32 2002/08/14 22:29:52 mj Exp $"""
from DT_String import String, FileMixin
import DT_String, re
......@@ -71,7 +71,7 @@ class dtml_re_class:
else:
if text[s:s+5] == '&dtml' and text[s+5] in '.-':
n=s+6
e=text.find(';',n)
e=text.find(';',n)
if e >= 0:
args=text[n:e]
l=len(args)
......@@ -97,7 +97,7 @@ class dtml_re_class:
d[3]=d['args']=args
self._start = s
return self
start=s+1
continue
......@@ -106,7 +106,7 @@ class dtml_re_class:
mo = name_match(text,n)
if mo is None: return None
l = mo.end(0) - mo.start(0)
a=n+l
name=text[n:a].strip()
......@@ -177,7 +177,7 @@ class HTML(DT_String.String):
if not (args==sargs or
args==sargs[:l] and sargs[l:l+1] in ' \t\n'):
return tag, args, self.commands[name], None
return tag, args, None, name
try: return tag, args, self.commands[name], None
......@@ -225,7 +225,7 @@ class HTML(DT_String.String):
manage_editForm__roles__=()
def manage_editForm(self, URL1, REQUEST):
'''Display doc template editing form''' #"
return self._manage_editForm(
self,
mapping=REQUEST,
......@@ -302,7 +302,7 @@ class HTMLFile(FileMixin, HTML):
if data.find('\r'):
data='\n\r'.join(data.split('\r\n'))
data='\n'.join(data.split('\n\r'))
if self.edited_source:
self.edited_source=data
self._v_cooked=self.cook()
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
__doc__='''Conditional insertion
......@@ -19,14 +19,14 @@ __doc__='''Conditional insertion
format, use::
%(if name)[
text
text
%(if name)]
To include text when an object is true using the HTML
format, use::
<!--#if name-->
text
text
<!--#/if name-->
where 'name' is the name bound to the object.
......@@ -35,14 +35,14 @@ __doc__='''Conditional insertion
format, use::
%(else name)[
text
text
%(else name)]
To include text when an object is false using the HTML
format, use::
<!--#else name-->
text
text
<!--#/else name-->
Finally to include text when an object is true and to
......@@ -50,10 +50,10 @@ __doc__='''Conditional insertion
EPFS format, use::
%(if name)[
true text
true text
%(if name)]
%(else name)[
false text
false text
%(else name)]
and to include text when an object is true and to
......@@ -61,9 +61,9 @@ __doc__='''Conditional insertion
HTML format, use::
<!--#if name-->
true text
true text
<!--#else name-->
false text
false text
<!--#/if name-->
Notes:
......@@ -74,9 +74,9 @@ __doc__='''Conditional insertion
is used inside the tag, including in enclosed tags, the
variable is not reevaluated.
'''
__rcs_id__='$Id: DT_If.py,v 1.18 2001/11/28 15:50:54 matt Exp $'
__version__='$Revision: 1.18 $'[11:-2]
'''
__rcs_id__='$Id: DT_If.py,v 1.19 2002/08/14 22:29:52 mj Exp $'
__version__='$Revision: 1.19 $'[11:-2]
from DT_Util import ParseError, parse_params, name_param, str
......
This diff is collapsed.
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
__doc__='''Sequence variables support
$Id: DT_InSV.py,v 1.21 2001/11/28 15:50:54 matt Exp $'''
__version__='$Revision: 1.21 $'[11:-2]
$Id: DT_InSV.py,v 1.22 2002/08/14 22:29:52 mj Exp $'''
__version__='$Revision: 1.22 $'[11:-2]
from math import sqrt
import re
......@@ -28,10 +28,10 @@ except: mv=None
class sequence_variables:
alt_prefix = None
def __init__(self,items=None,query_string='',start_name_re=None,
alt_prefix=''):
self.items=items
self.query_string=query_string
self.start_name_re=start_name_re
......@@ -68,35 +68,35 @@ class sequence_variables:
roman = ''
while num >= 1000:
num = num - 1000
roman = '%sM' % roman
num = num - 1000
roman = '%sM' % roman
while num >= 500:
num = num - 500
roman = '%sD' % roman
num = num - 500
roman = '%sD' % roman
while num >= 100:
num = num - 100
roman = '%sC' % roman
num = num - 100
roman = '%sC' % roman
while num >= 50:
num = num - 50
roman = '%sL' % roman
num = num - 50
roman = '%sL' % roman
while num >= 10:
num = num - 10
roman = '%sX' % roman
num = num - 10
roman = '%sX' % roman
while num >= 5:
num = num - 5
roman = '%sV' % roman
num = num - 5
roman = '%sV' % roman
while num < 5 and num >= 1:
num = num - 1
roman = '%sI' % roman
num = num - 1
roman = '%sI' % roman
# Replaces special cases in Roman Numerals
roman = roman.replace('DCCCC', 'CM')
roman = roman.replace('CCCC', 'CD')
roman = roman.replace('LXXXX', 'XC')
......@@ -132,7 +132,7 @@ class sequence_variables:
return l
def query(self, *ignored):
if self.start_name_re is None: raise KeyError, 'sequence-query'
query_string=self.query_string
while query_string and query_string[:1] in '?&':
......@@ -140,7 +140,7 @@ class sequence_variables:
while query_string[-1:] == '&':
query_string=query_string[:-1]
if query_string:
query_string='&%s&' % query_string
query_string='&%s&' % query_string
reg=self.start_name_re
if type(reg)==type(re.compile(r"")):
......@@ -160,9 +160,9 @@ class sequence_variables:
query_string='?'+query_string[1:]
else: query_string='?'
self['sequence-query']=query_string
return query_string
statistic_names=(
'total', 'count', 'min', 'max', 'median', 'mean',
......@@ -225,7 +225,7 @@ class sequence_variables:
if count > 1:
sumsq=sumsq*n/(n-1)
data['variance-%s' % name]=sumsq
data['standard-deviation-%s' % name]=sqrt(sumsq)
data['standard-deviation-%s' % name]=sqrt(sumsq)
else:
data['variance-%s' % name]=''
data['standard-deviation-%s' % name]=''
......@@ -368,7 +368,7 @@ class sequence_variables:
except: pass
if key=='sequence-query': return self.query()
raise KeyError, key
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
''' The Let tag was contributed to Zope by and is copyright, 1999
Phillip J. Eby. Permission has been granted to release the Let tag
under the Zope Public License.
Let name=value...
......@@ -38,7 +38,7 @@
Variables are processed in sequence, so later assignments can
reference and/or overwrite the results of previous assignments,
as desired.
'''
'''
from DT_Util import render_blocks, Eval, ParseError
from DT_Util import str # Probably needed due to hysterical pickles.
......@@ -48,7 +48,7 @@ import re
class Let:
blockContinuations=()
name='let'
def __init__(self, blocks):
tname, args, section = blocks[0]
self.__name__ = args
......@@ -58,7 +58,7 @@ class Let:
for i in range(len(args)):
name,expr = args[i]
if expr[:1]=='"' and expr[-1:]=='"' and len(expr) > 1:
# expr shorthand
# expr shorthand
expr=expr[1:-1]
try: args[i] = name, Eval(expr).eval
except SyntaxError, v:
......@@ -85,7 +85,7 @@ def parse_let_params(text,
parmre=re.compile('([\000- ]*([^\000- ="]+)=([^\000- ="]+))'),
qparmre=re.compile('([\000- ]*([^\000- ="]+)="([^"]*)")'),
**parms):
result=result or []
mo = parmre.match(text)
......@@ -108,4 +108,3 @@ def parse_let_params(text,
text=text[l:].strip()
if text: return apply(parse_let_params,(text,result,tag),parms)
else: return result
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
'''Raising exceptions
......@@ -22,9 +22,9 @@
<!--#/raise-->
<!--#/if-->
'''
__rcs_id__='$Id: DT_Raise.py,v 1.12 2001/11/28 15:50:55 matt Exp $'
__version__='$Revision: 1.12 $'[11:-2]
'''
__rcs_id__='$Id: DT_Raise.py,v 1.13 2002/08/14 22:29:52 mj Exp $'
__version__='$Revision: 1.13 $'[11:-2]
from DT_Util import parse_params, name_param, render_blocks, str
......@@ -43,9 +43,9 @@ class Raise:
def render(self,md):
expr=self.expr
if expr is None:
t=self.__name__
if t[-5:]=='Error' and __builtins__.has_key(t):
t=__builtins__[t]
t=self.__name__
if t[-5:]=='Error' and __builtins__.has_key(t):
t=__builtins__[t]
else:
try: t=expr.eval(md)
except: t='Invalid Error Type Expression'
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
__version__='$Revision: 1.6 $'[11:-2]
__version__='$Revision: 1.7 $'[11:-2]
from DT_Util import parse_params, name_param, str
import sys
class ReturnTag:
class ReturnTag:
name='return'
expr=None
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"$Id: DT_String.py,v 1.50 2002/08/01 16:00:39 mj Exp $"
"$Id: DT_String.py,v 1.51 2002/08/14 22:29:52 mj Exp $"
import thread,re,exceptions,os
......@@ -36,7 +36,7 @@ class String:
%(name)s
%(in results)]
"""
"""
isDocTemp=1
......@@ -46,7 +46,7 @@ class String:
func_code.co_varnames='self','REQUEST'
func_code.co_argcount=2
func_code.__roles__=()
func_defaults__roles__=()
func_defaults=()
......@@ -186,7 +186,7 @@ class String:
def skip_eol(self, text, start, eol=re.compile('[ \t]*\n')):
# if block open is followed by newline, then skip past newline
mo =eol.match(text,start)
if mo is not None:
if mo is not None:
start = start + mo.end(0) - mo.start(0)
return start
......@@ -210,7 +210,7 @@ class String:
try: tag, args, command, coname= self._parseTag(mo,scommand,sa)
except ParseError, m: self.parse_error(m[0],m[1], text, l)
if command:
start=l+len(tag)
if hasattr(command, 'blockContinuations'):
......@@ -223,7 +223,7 @@ class String:
section._v_blocks=section.blocks=self.parse(text[:l],sstart)
section._v_cooked=None
blocks.append((tname,sargs,section))
start=self.skip_eol(text,l+len(tag))
if coname:
......@@ -315,7 +315,7 @@ class String:
"""
if mapping is not None or vars:
self.initvars(mapping, vars)
if source_string is not None:
if source_string is not None:
self.raw=source_string
self.cook()
......@@ -371,13 +371,13 @@ class String:
containing values to be looked up. Values will be looked up
using getattr, so inheritence of values is supported. Note
that names beginning with '_' will not be looked up from the
client.
client.
The optional argument, 'mapping' is used to specify a mapping
object containing values to be inserted.
Values to be inserted may also be specified using keyword
arguments.
arguments.
Values will be inserted from one of several sources. The
sources, in the order in which they are consulted, are:
......@@ -392,7 +392,7 @@ class String:
created, and
o The 'mapping' argument provided when the template was
created.
created.
'''
# print '============================================================'
......@@ -459,8 +459,8 @@ class String:
# otherwise its just a normal client object.
push(InstanceDict(client, md)) # Circ. Ref. 8-|
pushed=pushed+1
if self._vars:
if self._vars:
push(self._vars)
pushed=pushed+1
......@@ -498,7 +498,7 @@ class String:
class FileMixin:
# Mix-in class to abstract certain file-related attributes
edited_source=''
def __init__(self, file_name='', mapping=None, __name__='', **vars):
"""\
Create a document template based on a named file.
......@@ -515,7 +515,7 @@ class FileMixin:
if self.edited_source: return self.edited_source
if not os.path.exists(self.raw):
print 'file not found: %s' % self.raw
if self.raw: return open(self.raw,'r').read()
return ''
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
import sys, traceback
......@@ -19,41 +19,41 @@ from DT_Return import DTReturn
class Try:
"""Zope DTML Exception handling
usage:
<!--#try-->
<!--#except SomeError AnotherError-->
<!--#except YetAnotherError-->
<!--#except-->
<!--#else-->
<!--#/try-->
or:
<!--#try-->
<!--#finally-->
<!--#/try-->
The DTML try tag functions quite like Python's try command.
The contents of the try tag are rendered. If an exception is raised,
then control switches to the except blocks. The first except block to
match the type of the error raised is rendered. If an except block has
no name then it matches all raised errors.
The try tag understands class-based exceptions, as well as string-based
exceptions. Note: the 'raise' tag raises string-based exceptions.
Inside the except blocks information about the error is available via
three variables.
'error_type' -- This variable is the name of the exception caught.
'error_value' -- This is the caught exception's value.
'error_tb' -- This is a traceback for the caught exception.
The optional else block is rendered when no exception occurs in the
try block. Exceptions in the else block are not handled by the preceding
except blocks.
......@@ -78,10 +78,10 @@ class Try:
lost.
Original version by Jordan B. Baker.
Try..finally and try..else implementation by Martijn Pieters.
"""
name = 'try'
blockContinuations = 'except', 'else', 'finally'
finallyBlock=None
......@@ -158,7 +158,7 @@ class Try:
errname = t.__name__
handler = self.find_handler(t)
if handler is None:
# we didn't find a handler, so reraise the error
raise
......@@ -181,7 +181,7 @@ class Try:
return result
else:
return result + render_blocks(self.elseBlock, md)
def render_try_finally(self, md):
result = ''
# first try to render the first block
......@@ -202,13 +202,13 @@ class Try:
return None
for e,h in self.handlers:
if e==exception.__name__ or e=='' or self.match_base(exception,e):
return h
return None
return h
return None
def match_base(self,exception,name):
for base in exception.__bases__:
if base.__name__==name or self.match_base(base,name):
return 1
return None
__call__ = render
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
__doc__='''Machinery to support through-the-web editing
$Id: DT_UI.py,v 1.11 2001/11/28 15:50:55 matt Exp $'''
__version__='$Revision: 1.11 $'[11:-2]
$Id: DT_UI.py,v 1.12 2002/08/14 22:29:52 mj Exp $'''
__version__='$Revision: 1.12 $'[11:-2]
from DT_HTML import HTML
......@@ -35,13 +35,13 @@ HTML._manage_editForm = HTML(
</HEAD>
<BODY bgcolor="#FFFFFF">
<!--#var document_template_edit_header-->
<FORM name="editform" ACTION="<!--#var URL1-->/manage_edit" METHOD="POST">
<!--#var document_template_form_header-->
Document template source:
<center>
<br>
<TEXTAREA NAME="data:text" cols="<!--#var document_template_edit_width-->"
<TEXTAREA NAME="data:text" cols="<!--#var document_template_edit_width-->"
rows="20"><!--#var __str__--></TEXTAREA>
<br>
......@@ -50,12 +50,12 @@ HTML._manage_editForm = HTML(
<INPUT NAME="dt_edit_name" TYPE="HIDDEN"
VALUE="<!--#var URL1-->">
<!--#if FactoryDefaultString-->
<INPUT NAME=SUBMIT TYPE="SUBMIT"
<INPUT NAME=SUBMIT TYPE="SUBMIT"
VALUE="<!--#var FactoryDefaultString-->">
<!--#/if FactoryDefaultString-->
<INPUT NAME=SUBMIT TYPE="SUBMIT" VALUE="Cancel">
<!--#if HTTP_REFERER-->
<INPUT NAME="CANCEL_ACTION" TYPE="HIDDEN"
<INPUT NAME="CANCEL_ACTION" TYPE="HIDDEN"
VALUE="<!--#var HTTP_REFERER-->">
<!--#else HTTP_REFERER-->
<!--#if URL1-->
......@@ -65,10 +65,10 @@ HTML._manage_editForm = HTML(
<!--#/if HTTP_REFERER-->
</center>
</FORM>
<BR CLEAR="ALL">
<!--#var document_template_edit_footer-->
</BODY>
</HTML>""",)
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
'''$Id: DT_Util.py,v 1.87 2002/08/01 16:00:39 mj Exp $'''
__version__='$Revision: 1.87 $'[11:-2]
'''$Id: DT_Util.py,v 1.88 2002/08/14 22:29:52 mj Exp $'''
__version__='$Revision: 1.88 $'[11:-2]
import re, os
from html_quote import html_quote, ustr # for import by other modules, dont remove!
......@@ -234,7 +234,7 @@ def name_param(params,tag='',expr=0, attr='name', default_unnamed=1):
# # Fix up something like: <!--#in expr="whatever" mapping-->
# params[params['']]=default_unnamed
# del params['']
if used(''):
v=params['']
......@@ -257,7 +257,7 @@ def name_param(params,tag='',expr=0, attr='name', default_unnamed=1):
'that doesn\'t support expr attributes.',
tag)
else: # name shorthand
else: # name shorthand
if used(attr):
raise ParseError, ('Two %s values were given' % attr, tag)
if expr:
......@@ -277,7 +277,7 @@ def name_param(params,tag='',expr=0, attr='name', default_unnamed=1):
name=params['expr']
expr=Eval(name)
return name, expr
raise ParseError, ('No %s given' % attr, tag)
Expr_doc="""
......@@ -308,20 +308,20 @@ Python expression support
mapping object. This variable can be useful for accessing objects
in a document template namespace that have names that are not legal
Python variable names::
<!--#var expr="_['sequence-number']*5"-->
This variable also has attributes that provide access to standard
utility objects. These attributes include:
- The objects: 'None', 'abs', 'chr', 'divmod', 'float', 'hash',
'hex', 'int', 'len', 'max', 'min', 'oct', 'ord', 'pow',
'round', and 'str' from the standard Python builtin module.
- Special security-aware versions of 'getattr' and 'hasattr',
- The Python 'string', 'math', and 'whrandom' modules, and
- A special function, 'test', that supports if-then expressions.
The 'test' function accepts any number of arguments. If the
first argument is true, then the second argument is returned,
......@@ -329,10 +329,10 @@ Python expression support
argument is returned, and so on. If there is an odd number of
arguments, then the last argument is returned in the case that
none of the tested arguments is true, otherwise None is
returned.
returned.
For example, to convert a value to lower case::
<!--#var expr="_.string.lower(title)"-->
"""
......@@ -370,7 +370,7 @@ def parse_params(text,
result=result or {}
# HACK - we precalculate all matches. Maybe we don't need them
# HACK - we precalculate all matches. Maybe we don't need them
# all. This should be fixed for performance issues
mo_p = parmre.match(text)
......@@ -393,7 +393,7 @@ def parse_params(text,
if parms.has_key(name):
if parms[name] is None: raise ParseError, (
'Attribute %s requires a value' % name, tag)
result[name]=parms[name]
else: raise ParseError, (
'Invalid attribute name, "%s"' % name, tag)
......@@ -410,7 +410,7 @@ def parse_params(text,
else:
if not text or not text.strip(): return result
raise ParseError, ('invalid parameter: "%s"' % text, tag)
if not parms.has_key(name):
raise ParseError, (
'Invalid attribute name, "%s"' % name, tag)
......@@ -420,7 +420,7 @@ def parse_params(text,
if type(p) is not ListType or p:
raise ParseError, (
'Duplicate values for attribute "%s"' % name, tag)
result[name]=value
text=text[l:].strip()
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
__doc__='''Variable insertion parameters
......@@ -58,7 +58,7 @@ __doc__='''Variable insertion parameters
- Cannot be formatted with the specified format, and
- Are either the special Python value 'None' or
- Are either the special Python value 'None' or
are false and yield an empty string when converted to
a string.
......@@ -89,12 +89,12 @@ __doc__='''Variable insertion parameters
value after formatting has been applied. These parameters
are supplied without arguments.
'lower' -- cause all upper-case letters to be converted to lower case.
'lower' -- cause all upper-case letters to be converted to lower case.
'upper' -- cause all upper-case letters to be converted to lower case.
'upper' -- cause all upper-case letters to be converted to lower case.
'capitalize' -- cause the first character of the inserted value
to be converted to upper case.
to be converted to upper case.
'spacify' -- cause underscores in the inserted value to be
converted to spaces.
......@@ -140,7 +140,7 @@ __doc__='''Variable insertion parameters
truncation, the value given for the 'etc' attribute is added to
the string. If the 'etc' attribute is not provided, then '...'
is used. For example, if the value of spam is
'"blah blah blah blah"', then the tag
'"blah blah blah blah"', then the tag
'<dtml-var spam size=10>' inserts '"blah blah ..."'.
......@@ -148,11 +148,11 @@ Evaluating expressions without rendering results
A 'call' tag is provided for evaluating named objects or expressions
without rendering the result.
''' # '
__rcs_id__='$Id: DT_Var.py,v 1.56 2002/08/14 16:34:20 rdmurray Exp $'
__version__='$Revision: 1.56 $'[11:-2]
__rcs_id__='$Id: DT_Var.py,v 1.57 2002/08/14 22:29:52 mj Exp $'
__version__='$Revision: 1.57 $'[11:-2]
from DT_Util import parse_params, name_param, str, ustr
import os, string, re, sys
......@@ -163,7 +163,7 @@ from types import StringType
from Acquisition import aq_base
from ZPublisher.TaintedString import TaintedString
class Var:
class Var:
name='var'
expr=None
......@@ -177,7 +177,7 @@ class Var:
url_unquote_plus=1,missing='',
newline_to_br=1, url=1)
self.args=args
self.modifiers=tuple(
map(lambda t: t[1],
filter(lambda m, args=args, used=args.has_key:
......@@ -226,7 +226,7 @@ class Var:
if have_arg('null') and not val and val != 0:
# check for null (false but not zero, including None, [], '')
return args['null']
# handle special formats defined using fmt= first
if have_arg('fmt'):
......@@ -248,7 +248,7 @@ class Var:
else:
val = special_formats[fmt](val, name, md)
elif fmt=='': val=''
else:
else:
if isinstance(val, TaintedString):
val = TaintedString(fmt % val)
else:
......@@ -317,12 +317,12 @@ class Var:
if isinstance(val, TaintedString):
val = val.quoted()
return val
__call__=render
class Call:
class Call:
name='call'
expr=None
......@@ -379,7 +379,7 @@ def thousands_commas(v, name='(Unknown name)', md={},
v=v[:l+1]+','+v[l+1:]
mo=thou(v)
return v+s
def whole_dollars_with_commas(v, name='(Unknown name)', md={}):
try: v= "$%d" % v
except: v=''
......@@ -399,7 +399,7 @@ def len_comma(v, name='(Unknown name)', md={}):
StructuredText=None
def structured_text(v, name='(Unknown name)', md={}):
global StructuredText
if StructuredText is None:
if StructuredText is None:
from StructuredText.StructuredText import HTML
if isinstance(v,StringType): txt = v
......@@ -408,11 +408,11 @@ def structured_text(v, name='(Unknown name)', md={}):
txt = aq_base(v).read_raw()
else: txt = str(v)
return HTML(txt,
return HTML(txt,
level=int(os.environ.get('STX_DEFAULT_LEVEL',3)),
header=0)
def sql_quote(v, name='(Unknown name)', md={}):
"""Quote single quotes in a string by doubling them.
......@@ -457,15 +457,15 @@ class Comment:
The 'comment' tag can be used to simply include comments
in DTML source.
For example::
<!--#comment-->
This text is not rendered.
<!--#/comment-->
'''
'''
name='comment'
blockContinuations=()
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
'''Nested namespace access
......@@ -31,10 +31,10 @@
should be treated as mapping object, rather than as an object with
named attributes.
'''
'''
__rcs_id__='$Id: DT_With.py,v 1.14 2001/11/28 15:50:55 matt Exp $'
__version__='$Revision: 1.14 $'[11:-2]
__rcs_id__='$Id: DT_With.py,v 1.15 2002/08/14 22:29:52 mj Exp $'
__version__='$Revision: 1.15 $'[11:-2]
from DT_Util import parse_params, name_param, InstanceDict, render_blocks, str
from DT_Util import TemplateDict
......@@ -43,7 +43,7 @@ class With:
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)
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
__doc__='''short description
$Id: DTtestExpr.py,v 1.7 2001/11/28 15:50:55 matt Exp $'''
__version__='$Revision: 1.7 $'[11:-2]
$Id: DTtestExpr.py,v 1.8 2002/08/14 22:29:52 mj Exp $'''
__version__='$Revision: 1.8 $'[11:-2]
from DocumentTemplate import *
import sys
......@@ -47,7 +47,7 @@ def test4():
print '-' * 77
print i, h(level=i)
print '-' * 77
if __name__ == "__main__":
try: command=sys.argv[1]
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
'''Document templates with fill-in fields
......@@ -60,7 +60,7 @@ Two source formats are supported:
<!--#var total fmt=12.2f-->
is used to insert the variable 'total' with the C format
'12.2f'.
'12.2f'.
Document templates support conditional and sequence insertion
......@@ -105,7 +105,7 @@ Document Templates may be created 4 ways:
'''
__version__='$Revision: 1.13 $'[11:-2]
__version__='$Revision: 1.14 $'[11:-2]
ParseError='Document Template Parse Error'
......
......@@ -7,4 +7,3 @@ def careful_mul(env, *factors):
for factor in factors:
r=r*factor
return r
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
__doc__='''Package wrapper for Document Template
This wrapper allows the (now many) document template modules to be
segregated in a separate package.
$Id: __init__.py,v 1.16 2001/11/28 15:50:55 matt Exp $'''
__version__='$Revision: 1.16 $'[11:-2]
$Id: __init__.py,v 1.17 2002/08/14 22:29:53 mj Exp $'''
__version__='$Revision: 1.17 $'[11:-2]
import ExtensionClass # work-around for import bug.
from DocumentTemplate import String, File, HTML, HTMLDefault, HTMLFile
......@@ -5,4 +5,3 @@ from ustr import ustr
def html_quote(v, name='(Unknown name)', md={}):
return escape(ustr(v), 1)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
__doc__='''Python implementations of document template some features
$Id: pDocumentTemplate.py,v 1.35 2002/03/27 10:14:02 htrd Exp $'''
__version__='$Revision: 1.35 $'[11:-2]
$Id: pDocumentTemplate.py,v 1.36 2002/08/14 22:29:53 mj Exp $'''
__version__='$Revision: 1.36 $'[11:-2]
import sys, types
......@@ -69,7 +69,7 @@ class InstanceDict:
cache=self.cache
if cache.has_key(key): return cache[key]
inst=self.self
if key[:1]=='_':
......@@ -115,14 +115,14 @@ class MultiMapping:
return kz
class DictInstance:
def __init__(self, mapping):
self.__d=mapping
def __getattr__(self, name):
try: return self.__d[name]
except KeyError: raise AttributeError, name
class TemplateDict:
level=0
......@@ -152,10 +152,10 @@ class TemplateDict:
return v
def __len__(self):
total = 0
for d in self.dicts.dicts:
total = total + len(d)
return total
total = 0
for d in self.dicts.dicts:
total = total + len(d)
return total
def has_key(self,key):
try:
......@@ -163,7 +163,7 @@ class TemplateDict:
except KeyError:
return 0
return 1
getitem=__getitem__
def __call__(self, *args, **kw):
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""
Advanced sort support by Oleg Broytmann <phd@@phd.pp.ru> 23 Apr 2001
eg Sort(sequence, (("akey", "nocase"), ("anotherkey", "cmp", "desc")))
$Id: SortEx.py,v 1.4 2002/02/07 17:47:42 andreasjung Exp $
$Id: SortEx.py,v 1.5 2002/08/14 22:29:53 mj Exp $
"""
......@@ -36,19 +36,19 @@ def sort(sequence, sort=(), _=None, mapping=0):
allowed values:
- "cmp" -- the standard comparison function (default)
- "nocase" -- case-insensitive comparison
- "strcoll" or "locale" -- locale-aware string comparison
- "strcoll_nocase" or "locale_nocase" -- locale-aware case-insensitive
string comparison
- "xxx" -- a user-defined comparison function
- direction -- defines the sort direction for the key (optional).
(allowed values: "asc" (default) , "desc")
"""
"""
......@@ -60,7 +60,7 @@ def sort(sequence, sort=(), _=None, mapping=0):
need_sortfunc = 1
break
sortfields = sort # multi sort = key1,key2
sortfields = sort # multi sort = key1,key2
multsort = len(sortfields) > 1 # flag: is multiple sort
if need_sortfunc:
......@@ -92,25 +92,25 @@ def sort(sequence, sort=(), _=None, mapping=0):
v=client
if sort:
if multsort: # More than one sort key.
k = []
for sk in sortfields:
try:
if mapping: akey = v[sk]
else: akey = getattr(v, sk)
except AttributeError, KeyError: akey = None
if not basic_type(akey):
try: akey = akey()
except: pass
k.append(akey)
else: # One sort key.
try:
if mapping: k = v[sort]
else: k = getattr(v, sort)
except AttributeError, KeyError: k = None
if not basic_type(type(k)):
try: k = k()
except: pass
if multsort: # More than one sort key.
k = []
for sk in sortfields:
try:
if mapping: akey = v[sk]
else: akey = getattr(v, sk)
except AttributeError, KeyError: akey = None
if not basic_type(akey):
try: akey = akey()
except: pass
k.append(akey)
else: # One sort key.
try:
if mapping: k = v[sort]
else: k = getattr(v, sort)
except AttributeError, KeyError: k = None
if not basic_type(type(k)):
try: k = k()
except: pass
s.append((k,client))
......@@ -122,7 +122,7 @@ def sort(sequence, sort=(), _=None, mapping=0):
sequence=[]
for k, client in s:
sequence.append(client)
sequence.append(client)
return sequence
......@@ -219,5 +219,3 @@ class SortBy:
# all functions returned 0 - identical sequences
return 0
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
import os, sys, unittest
......@@ -30,7 +30,7 @@ class TestCase( unittest.TestCase ):
def tearDown( self ):
"""
"""
def test1( self ):
"test1"
assert res1==SortEx(wordlist)
......@@ -42,7 +42,7 @@ class TestCase( unittest.TestCase ):
def test3( self ):
"test3"
assert res3==SortEx(wordlist, (("key", "cmp"),), mapping=1)
def test4( self ):
"test4"
assert res4==SortEx(wordlist, (("key", "cmp", "desc"),), mapping=1)
......@@ -60,7 +60,7 @@ class TestCase( unittest.TestCase ):
"test7"
def myCmp(s1, s2):
return -cmp(s1, s2)
return -cmp(s1, s2)
# Create namespace...
from DocumentTemplate.DT_Util import TemplateDict
......
class standard_html: # Base class for using with ZTemplates
def __init__(self, title):
self.standard_html_header = """<HTML>
def __init__(self, title):
self.standard_html_header = """<HTML>
<HEAD>
<TITLE>
%s
......@@ -11,25 +9,25 @@ class standard_html: # Base class for using with ZTemplates
<BODY>""" % title
self.standard_html_footer = """</BODY>
self.standard_html_footer = """</BODY>
</HTML>"""
self.title = title
self.title = title
def test(s):
outfile = open("test.out", 'w')
outfile.write(s)
outfile.close()
outfile = open("test.out", 'w')
outfile.write(s)
outfile.close()
def exception():
import sys, traceback
exc_type, exc_value, exc_tb = sys.exc_info()
import sys, traceback
exc_type, exc_value, exc_tb = sys.exc_info()
outfile = open("test.err", 'w')
traceback.print_exception(exc_type, exc_value, exc_tb, None, outfile)
outfile.close()
outfile = open("test.err", 'w')
traceback.print_exception(exc_type, exc_value, exc_tb, None, outfile)
outfile.close()
wordlist = [
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""Document Template Tests
"""
__rcs_id__='$Id: testDTML.py,v 1.13 2002/08/14 15:46:58 chrism Exp $'
__version__='$Revision: 1.13 $'[11:-2]
__rcs_id__='$Id: testDTML.py,v 1.14 2002/08/14 22:29:53 mj Exp $'
__version__='$Revision: 1.14 $'[11:-2]
import sys, os
import unittest
......@@ -259,7 +259,7 @@ class DTMLTests (unittest.TestCase):
<dtml-var expr="'http%3A%2F%2Fwww.zope.org%3Fa%3Db+123'" fmt=url-unquote-plus>
"""
)
expected = (
"""
http://www.zope.org?a=b 123
......@@ -277,7 +277,7 @@ class DTMLTests (unittest.TestCase):
<dtml-var expr="'http%3A%2F%2Fwww.zope.org%3Fa%3Db+123'" url_unquote_plus>
"""
)
expected = (
"""
http://www.zope.org?a=b 123
......@@ -285,7 +285,7 @@ class DTMLTests (unittest.TestCase):
)
self.assertEqual(html1(), expected)
self.assertEqual(html2(), expected)
def test_fmt(self):
html=self.doc_class(
......@@ -499,7 +499,7 @@ foo bar
"""
result = self.doc_class(html)(xxx=xxx, data={})
assert result == expected, result
def testBasicStringIn(self):
data=(
d(name='jim', age=39),
......@@ -522,7 +522,7 @@ foo bar
"""
result = String(s)(data=data)
assert expected == result, result
def test_suite():
suite = unittest.TestSuite()
suite.addTest( unittest.makeSuite( DTMLTests ) )
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""Document Template Tests
"""
__rcs_id__='$Id: testDTMLUnicode.py,v 1.2 2002/03/27 10:14:02 htrd Exp $'
__version__='$Revision: 1.2 $'[11:-2]
__rcs_id__='$Id: testDTMLUnicode.py,v 1.3 2002/08/14 22:29:53 mj Exp $'
__version__='$Revision: 1.3 $'[11:-2]
import sys, os
import unittest
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""Document Template Tests
"""
__rcs_id__='$Id: testustr.py,v 1.2 2002/03/27 10:14:02 htrd Exp $'
__version__='$Revision: 1.2 $'[11:-2]
__rcs_id__='$Id: testustr.py,v 1.3 2002/08/14 22:29:53 mj Exp $'
__version__='$Revision: 1.3 $'[11:-2]
import sys, os
import unittest
......
......@@ -8,7 +8,7 @@
foobarsize = s.foo.bar.restricted_exec('len(context.objectIds())')
'''
from Products.PythonScripts.PythonScript import PythonScript
from string import join
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""Python Scripts Product
......@@ -17,7 +17,7 @@ This product provides support for Script objects containing restricted
Python code.
"""
__version__='$Revision: 1.42 $'[11:-2]
__version__='$Revision: 1.43 $'[11:-2]
import sys, os, traceback, re, marshal
from Globals import DTMLFile, MessageDialog, package_home
......@@ -153,11 +153,11 @@ class PythonScript(Script, Historical, Cacheable):
"""Replace the body of the script with the text in file."""
if self.wl_isLocked():
raise ResourceLockedError, "The script is locked via WebDAV."
if type(file) is not type(''):
if type(file) is not type(''):
if not file: raise ValueError, 'File not specified'
file = file.read()
self.write(file)
message = 'Saved changes.'
return self.ZPythonScriptHTML_editForm(self, REQUEST,
......@@ -183,7 +183,7 @@ class PythonScript(Script, Historical, Cacheable):
"""Parameters to test the script with."""
param_names = []
for name in self._params.split(','):
name = name.strip()
if name and name[0] != '*' and re.match('\w',name):
param_names.append(name.split('=', 1)[0])
......@@ -201,7 +201,7 @@ class PythonScript(Script, Historical, Cacheable):
getattr(self, 'Script_magic', None) != Script_magic):
global _log_complaint
if _log_complaint:
LOG(self.meta_type, INFO, _log_complaint)
LOG(self.meta_type, INFO, _log_complaint)
_log_complaint = 0
# Changes here won't get saved, unless this Script is edited.
body = self._body.rstrip()
......@@ -329,7 +329,7 @@ class PythonScript(Script, Historical, Cacheable):
if user is not None and user.allowed(self, roles):
return
raise 'Forbidden', ('You are not authorized to change <em>%s</em> '
'because you do not have proxy roles.\n<!--%s, %s-->'
'because you do not have proxy roles.\n<!--%s, %s-->'
% (self.id, user, roles))
security.declareProtected('Change proxy roles',
......@@ -358,7 +358,7 @@ class PythonScript(Script, Historical, Cacheable):
self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1)
self.write(REQUEST.get('BODY', ''))
RESPONSE.setStatus(204)
return RESPONSE
return RESPONSE
manage_FTPput = PUT
......@@ -449,7 +449,7 @@ class PythonScript(Script, Historical, Cacheable):
hlines = ['%s %s "%s"' % (prefix, self.meta_type, self.id)]
mm = self._metadata_map().items()
mm.sort()
for kv in mm:
for kv in mm:
hlines.append('%s=%s' % kv)
if self.errors:
hlines.append('')
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""Utility module for making simple security assertions for
Python scripts."""
__version__='$Revision: 1.5 $'[11:-2]
__version__='$Revision: 1.6 $'[11:-2]
# These have been relocated, and should be imported from AccessControl
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
__doc__='''Python Scripts Product Initialization
$Id: __init__.py,v 1.12 2002/06/20 14:48:38 Brian Exp $'''
__version__='$Revision: 1.12 $'[11:-2]
$Id: __init__.py,v 1.13 2002/08/14 22:25:08 mj Exp $'''
__version__='$Revision: 1.13 $'[11:-2]
import PythonScript
try:
......@@ -43,7 +43,7 @@ def initialize(context):
global _m
_m['recompile'] = recompile
_m['recompile__roles__'] = ('Manager',)
# utility stuff
def recompile(self):
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
def manage_addPythonScript(id, REQUEST=None):
......@@ -136,7 +136,7 @@ class PythonScript:
__extends__=(
'PythonScripts.Script.Script',
)
def ZPythonScriptHTML_editAction(REQUEST, title, params, body):
"""
......@@ -230,8 +230,3 @@ class PythonScript:
'text/plain' set on the RESPONSE.
"""
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
class Script:
......
......@@ -3,7 +3,7 @@ Products.PythonScripts.standard: Utility functions and classes
The functions and classes in this module are available from
Python-based scripts, DTML, and Page Templates.
"""
def whole_dollars(number):
......@@ -23,7 +23,7 @@ def structured_text(s):
See Also
"Structured-Text Rules":http://dev.zope.org/Members/jim/StructuredTextWiki/StructuredTextNGRules
"""
def sql_quote(s):
......@@ -41,7 +41,7 @@ def html_quote(s):
"Python 'cgi' module":http://www.python.org/doc/current/lib/Functions_in_cgi_module.html
'escape' function.
"""
def url_quote(s):
......@@ -123,7 +123,7 @@ class DTML:
def call(client=None, REQUEST={}, **kw):
"""
Render the DTML.
To accomplish its task, DTML often needs to resolve various
names into objects. For example, when the code &lt;dtml-var
spam&gt; is executed, the DTML engine tries to resolve the
......@@ -148,5 +148,5 @@ class DTML:
three methods. You can pass any number of them or none at
all. Names will be looked up first in the keyword argument,
next in the client and finally in the mapping.
"""
......@@ -65,8 +65,3 @@ from Globals import InitializeClass
# 'error_reply', 'error_temp', 'error_perm', 'error_proto')
# from httplib import NNTP
# allow_class(NNTP)
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""Python Scripts standard utility module
......@@ -18,7 +18,7 @@ Scripts. It can be accessed from Python with the statement
"import Products.PythonScripts.standard"
"""
__version__='$Revision: 1.8 $'[11:-2]
__version__='$Revision: 1.9 $'[11:-2]
from AccessControl import ModuleSecurityInfo, getSecurityManager
security = ModuleSecurityInfo()
......@@ -53,4 +53,3 @@ class DTML(RestrictedDTML, HTML):
finally: security.removeContext(self)
security.apply(globals())
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
import os, sys, unittest
......@@ -74,9 +74,9 @@ class TestPythonScriptNoAq(unittest.TestCase):
assert txt == 'txt', txt
def testParam2(self):
one, two = self._newPS('##parameters=x,y\nreturn x,y')('one','two')
assert one == 'one'
assert two == 'two'
one, two = self._newPS('##parameters=x,y\nreturn x,y')('one','two')
assert one == 'one'
assert two == 'two'
def testParam26(self):
import string
......@@ -85,7 +85,7 @@ class TestPythonScriptNoAq(unittest.TestCase):
tup = apply(self._newPS('##parameters=%s\nreturn %s'
% (sparams,sparams)), params)
assert tup == tuple(params), (tup, params)
def testArithmetic(self):
one = self._newPS('return 1 * 5 + 4 / 2 - 6')()
assert one == 1, one
......@@ -103,7 +103,7 @@ class TestPythonScriptNoAq(unittest.TestCase):
def testForLoop(self):
ten = self._newPS(readf('for_loop'))()
assert ten == 10
def testMutateLiterals(self):
l, d = self._newPS(readf('mutate_literals'))()
assert l == [2], l
......@@ -122,7 +122,7 @@ class TestPythonScriptNoAq(unittest.TestCase):
a,b = self._newPS(readf('try_except'))()
assert a==1
assert b==1
def testBigBoolean(self):
true = self._newPS(readf('big_boolean'))()
assert true, true
......@@ -166,4 +166,3 @@ def main():
if __name__ == '__main__':
main()
############################################################################
#
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
......@@ -11,7 +11,7 @@
#
############################################################################
__version__='$Revision: 1.13 $'[11:-2]
__version__='$Revision: 1.14 $'[11:-2]
import Globals
from Persistence import Persistent
from ZODB import TimeStamp
......@@ -53,9 +53,9 @@ def constructBrowserIdManager(
ob = self._getOb(id)
if REQUEST is not None:
return self.manage_main(self, REQUEST, update_menu=1)
class BrowserIdManagerErr(Exception): pass
class BrowserIdManager(Item, Persistent, Implicit, RoleManager, Owned, Tabs):
""" browser id management class """
......@@ -99,7 +99,7 @@ class BrowserIdManager(Item, Persistent, Implicit, RoleManager, Owned, Tabs):
not create a browser id for the current request if one doesn't
already exist """
if self.getBrowserId(create=0): return 1
security.declareProtected(ACCESS_CONTENTS_PERM, 'getBrowserId')
def getBrowserId(self, create=1):
"""
......@@ -120,7 +120,7 @@ class BrowserIdManager(Item, Persistent, Implicit, RoleManager, Owned, Tabs):
# somebody screwed with the REQUEST instance during
# this request.
raise BrowserIdManagerErr, (
'Ill-formed browserid in REQUEST.browser_id_: %s' %
'Ill-formed browserid in REQUEST.browser_id_: %s' %
escape(bid)
)
return bid
......@@ -194,7 +194,7 @@ class BrowserIdManager(Item, Persistent, Implicit, RoleManager, Owned, Tabs):
# ns will be None if new, negating None below returns 1, which
# would indicate that it's new on this request
return not getattr(self.REQUEST, 'browser_id_ns_')
security.declareProtected(ACCESS_CONTENTS_PERM, 'encodeUrl')
def encodeUrl(self, url, create=1):
"""
......@@ -313,7 +313,7 @@ class BrowserIdManager(Item, Persistent, Implicit, RoleManager, Owned, Tabs):
if not (type(path) is type('') and not badcookiecharsin(path)):
raise BrowserIdManagerErr, 'Bad cookie path %s' % escape(repr(path))
self.cookie_path = path
security.declareProtected(ACCESS_CONTENTS_PERM, 'getCookiePath')
def getCookiePath(self):
""" """
......@@ -397,7 +397,7 @@ class BrowserIdManager(Item, Persistent, Implicit, RoleManager, Owned, Tabs):
A == leading-0-padded 8-char string-rep'd random integer
B == modified base64-encoded 11-char timestamp
To be URL-compatible, base64 encoding is modified as follows:
'=' end-padding is stripped off
'+' is translated to '-'
......@@ -428,14 +428,14 @@ class BrowserIdManager(Item, Persistent, Implicit, RoleManager, Owned, Tabs):
return # should we raise an exception?
if string.split(URL1,':')[0] != 'https':
return # should we raise an exception?
cookies = REQUEST.RESPONSE.cookies
cookie = cookies[self.browserid_name]= {}
for k,v in d.items():
if v:
cookie[k] = v #only stuff things with true values
cookie['value'] = bid
def _getB64TStamp(
self, b2a=binascii.b2a_base64,gmtime=time.gmtime, time=time.time,
b64_trans=b64_trans, split=string.split,
......
############################################################################
#
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
......@@ -103,7 +103,7 @@ class SessionDataManager(Item, Implicit, Persistent, RoleManager, Owned, Tabs):
security.declareProtected(ARBITRARY_SESSIONDATA_PERM,'getSessionDataByKey')
def getSessionDataByKey(self, key):
return self._getSessionDataObjectByKey(key)
security.declareProtected(ACCESS_CONTENTS_PERM, 'getBrowserIdManager')
def getBrowserIdManager(self):
""" """
......@@ -115,7 +115,7 @@ class SessionDataManager(Item, Implicit, Persistent, RoleManager, Owned, Tabs):
return mgr
# END INTERFACE METHODS
def __init__(self, id, path=None, title='', requestName=None):
self.id = id
self.setContainerPath(path)
......@@ -160,14 +160,14 @@ class SessionDataManager(Item, Implicit, Persistent, RoleManager, Owned, Tabs):
self.obpath = list(path) # sequence
else:
raise SessionDataManagerErr, ('Bad path value %s' % path)
security.declareProtected(MGMT_SCREEN_PERM, 'getContainerPath')
def getContainerPath(self):
""" """
if self.obpath is not None:
return string.join(self.obpath, '/')
return '' # blank string represents undefined state
def _hasSessionDataObject(self, key):
""" """
c = self._getSessionDataContainer()
......
############################################################################
#
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
......@@ -81,7 +81,7 @@ class BrowserIdManagerInterface(
"""
Returns true if browser id is 'new'. A browser id is 'new'
when it is first created and the client has therefore not sent it
back to the server in any request.
back to the server in any request.
Permission required: Access contents information
......@@ -111,7 +111,7 @@ class BrowserIdManagerInterface(
"""
Deletes the browser id cookie from the client browser, iff the
'cookies' browser id namespace is being used.
Permission required: Access contents information
Raises: BrowserIdManagerErr. If the 'cookies' namespace isn't
......@@ -123,7 +123,7 @@ class BrowserIdManagerInterface(
Sets the browser id cookie to browser id 'bid' by force.
Useful when you need to 'chain' browser id cookies across domains
for the same user (perhaps temporarily using query strings).
Permission required: Access contents information
Raises: BrowserIdManagerErr. If the 'cookies' namespace isn't
......
############################################################################
#
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""
Session initialization routines
$Id: __init__.py,v 1.6 2001/11/28 15:51:07 matt Exp $
$Id: __init__.py,v 1.7 2002/08/14 22:25:09 mj Exp $
"""
import ZODB # this is for testrunner to be happy
......
############################################################################
#
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
......
############################################################################
#
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
......@@ -81,7 +81,7 @@ class BrowserIdManagerInterface(
"""
Returns true if browser id is 'new'. A browser id is 'new'
when it is first created and the client has therefore not sent it
back to the server in any request.
back to the server in any request.
Permission required: Access contents information
......@@ -111,7 +111,7 @@ class BrowserIdManagerInterface(
"""
Deletes the browser id cookie from the client browser, iff the
'cookies' browser id namespace is being used.
Permission required: Access contents information
Raises: BrowserIdManagerErr. If the 'cookies' namespace isn't
......@@ -123,7 +123,7 @@ class BrowserIdManagerInterface(
Sets the browser id cookie to browser id 'bid' by force.
Useful when you need to 'chain' browser id cookies across domains
for the same user (perhaps temporarily using query strings).
Permission required: Access contents information
Raises: BrowserIdManagerErr. If the 'cookies' namespace isn't
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
import sys, os, time
if __name__ == "__main__":
......@@ -117,7 +117,7 @@ class TestMultiThread(TestCase):
time.sleep(0.1)
while threading.activeCount() > 1:
time.sleep(1)
def testNonOverlappingBrowserIds(self):
readers = []
writers = []
......@@ -143,7 +143,7 @@ class TestMultiThread(TestCase):
time.sleep(0.1)
while threading.activeCount() > 1:
time.sleep(1)
class BaseReaderWriter(threading.Thread):
def __init__(self, db, iters, sdm_name):
self.conn = db.open()
......@@ -180,7 +180,7 @@ class BaseReaderWriter(threading.Thread):
self.conn.close()
del self.app
print i
class ReaderThread(BaseReaderWriter):
def run1(self):
session_data_manager = getattr(self.app, self.sdm_name)
......@@ -216,4 +216,3 @@ def test_suite():
if __name__ == '__main__':
runner = TextTestRunner(verbosity=9, descriptions=9)
runner.run(test_suite())
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""
Test suite for session id manager.
$Id: testBrowserIdManager.py,v 1.10 2002/08/10 19:28:38 chrism Exp $
$Id: testBrowserIdManager.py,v 1.11 2002/08/14 22:25:10 mj Exp $
"""
__version__ = "$Revision: 1.10 $"[11:-2]
__version__ = "$Revision: 1.11 $"[11:-2]
import sys
import ZODB
......@@ -34,7 +34,7 @@ class TestBrowserIdManager(TestCase):
environ['SERVER_PORT']='80'
req = HTTPRequest(stdin, environ, resp)
self.m.REQUEST = req
def tearDown(self):
del self.m
......@@ -114,7 +114,7 @@ class TestBrowserIdManager(TestCase):
self.m.setCookieDomain('.zope.org')
setdomain = self.m.getCookieDomain()
self.failUnless( setdomain == '.zope.org', "%s" % setdomain )
def testSetCookieSecure(self):
self.m.setCookieSecure(1)
self.failUnless( self.m.getCookieSecure() == 1 )
......@@ -143,7 +143,7 @@ class TestBrowserIdManager(TestCase):
self.failUnless( not self.m.hasBrowserId() )
a = self.m.getBrowserId()
self.failUnless( self.m.hasBrowserId() )
def testBrowserIdIsNew(self):
a = self.m.getBrowserId()
self.failUnless( self.m.isBrowserIdNew() )
......@@ -178,7 +178,7 @@ class TestBrowserIdManager(TestCase):
a = self.m.getBrowserId()
self.failUnless( self.m.isBrowserIdFromCookie() )
self.failUnless( not self.m.isBrowserIdFromForm() )
def testIsBrowserIdFromFormOnly(self):
token = self.m.getBrowserId()
self.m.REQUEST.browser_id_ = token
......@@ -202,7 +202,7 @@ class TestBrowserIdManager(TestCase):
self.m.flushBrowserIdCookie()
c = self.m.REQUEST.RESPONSE.cookies[tokenkey]
self.failUnless( c['value'] == 'deleted' )
def testSetBrowserIdCookieByForce(self):
token = self.m.getBrowserId()
self.m.REQUEST.browser_id_ = token
......@@ -238,7 +238,7 @@ class TestBrowserIdManager(TestCase):
def test_suite():
testsuite = makeSuite(TestBrowserIdManager, 'test')
return testsuite
if __name__ == '__main__':
runner = TextTestRunner(verbosity=9)
runner.run(test_suite())
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
import sys, os, time
......@@ -92,11 +92,11 @@ def _populate(app):
app.temp_folder._setObject(toc_name, toc)
get_transaction().commit()
# index_html necessary for publishing emulation for testAutoReqPopulate
app._setObject('index_html', DTMLMethod('', __name__='foo'))
get_transaction().commit()
class TestBase(TestCase):
def setUp(self):
db = _getDB()
......@@ -137,7 +137,7 @@ class TestSessionManager(TestBase):
sd = self.app.session_data_manager.getSessionData(1)
sdm = aq_base(getattr(self.app, sdm_name))
toc = aq_base(getattr(self.app.temp_folder, toc_name))
self.failUnless(aq_base(sd.aq_parent) is sdm)
self.failUnless(aq_base(sd.aq_parent.aq_parent) is toc)
......@@ -229,4 +229,3 @@ def test_suite():
if __name__ == '__main__':
runner = TextTestRunner(verbosity=9, descriptions=9)
runner.run(test_suite())
......@@ -34,7 +34,7 @@ def _swallow(request, prefix):
def manage_addAccessRule(self, method_id=None, REQUEST=None, **ignored):
"""Point a __before_traverse__ entry at the specified method"""
# We want the original object, not stuff in between, and no acquisition
self = self.this()
self = self.this()
self = getattr(self, 'aq_base', self)
priority = (1, 'AccessRule')
......@@ -54,7 +54,7 @@ def manage_addAccessRule(self, method_id=None, REQUEST=None, **ignored):
except: pass
hook = AccessRule(method_id)
registerBeforeTraverse(self, hook, 'AccessRule', 1)
try:
try:
getattr(self, method_id).icon = 'misc_/SiteAccess/AccessRule.gif'
except: pass
if REQUEST:
......@@ -70,7 +70,7 @@ def manage_addAccessRule(self, method_id=None, REQUEST=None, **ignored):
def getAccessRule(self, REQUEST=None):
"Return the name of the current AccessRule, if any"
self = self.this()
self = self.this()
rules = queryBeforeTraverse(self, 'AccessRule')
if rules:
return rules[0][1].name
......
......@@ -28,7 +28,7 @@ def _cvt_btr(app):
btr[k] = NameCaller(v)
if touched:
rewriteBeforeTraverse(o, btr)
if __name__ == '__main__':
print "Converting SiteAccess objects from 1.x to 2.x ..."
app = Zope.app()
......
......@@ -36,9 +36,9 @@ class Traverser(Persistent, Item):
message='This object already contains a %s' % self.meta_type,
action=nextURL)
self.addToContainer(container)
if nextURL:
if nextURL:
return MessageDialog(title='Item Added',
message='This object now has a %s' % self.meta_type,
message='This object now has a %s' % self.meta_type,
action=nextURL)
def manage_beforeDelete(self, item, container):
......@@ -96,11 +96,11 @@ class SiteRoot(Traverser, Implicit):
'''Set the title, base, and path'''
self.__init__(title, base, path)
if REQUEST:
return MessageDialog(title='SiteRoot changed.',
message='The title is now "%s"<br>'
'The base is now "%s"<br>'
'The path is now "%s"<br>' % (title, base, path),
action='%s/manage_main' % REQUEST['URL1'])
return MessageDialog(title='SiteRoot changed.',
message='The title is now "%s"<br>'
'The base is now "%s"<br>'
'The path is now "%s"<br>' % (title, base, path),
action='%s/manage_main' % REQUEST['URL1'])
def __call__(self, client, request, response=None):
'''Traversing'''
......
......@@ -97,9 +97,9 @@ class VirtualHostMonster(Persistent, Item, Implicit):
def manage_addToContainer(self, container, nextURL=''):
self.addToContainer(container)
if nextURL:
if nextURL:
return MessageDialog(title='Item Added',
message='This object now has a %s' % self.meta_type,
message='This object now has a %s' % self.meta_type,
action=nextURL)
def manage_beforeDelete(self, item, container):
......
......@@ -3,15 +3,15 @@ __doc__="""SiteAccess product"""
import SiteRoot, AccessRule, VirtualHostMonster
def initialize(context):
context.registerClass(instance_class=SiteRoot.SiteRoot,
permission='Add Site Roots',
constructors=SiteRoot.constructors, legacy=SiteRoot.constructors,
icon='www/SiteRoot.gif')
context.registerClass(instance_class=AccessRule.AccessRule,
permission='Manage Access Rules', constructors=AccessRule.constructors,
icon='www/AccessRule.gif')
context.registerClass(instance_class=VirtualHostMonster.VirtualHostMonster,
permission='Add Virtual Host Monsters',
constructors=VirtualHostMonster.constructors,
icon='www/VirtualHostMonster.gif')
context.registerHelp()
context.registerClass(instance_class=SiteRoot.SiteRoot,
permission='Add Site Roots',
constructors=SiteRoot.constructors, legacy=SiteRoot.constructors,
icon='www/SiteRoot.gif')
context.registerClass(instance_class=AccessRule.AccessRule,
permission='Manage Access Rules', constructors=AccessRule.constructors,
icon='www/AccessRule.gif')
context.registerClass(instance_class=VirtualHostMonster.VirtualHostMonster,
permission='Add Virtual Host Monsters',
constructors=VirtualHostMonster.constructors,
icon='www/VirtualHostMonster.gif')
context.registerHelp()
......@@ -2,18 +2,18 @@
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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.
#
#
##############################################################################
"""Site error log module.
$Id: SiteErrorLog.py,v 1.9 2002/06/29 18:46:45 chrism Exp $
$Id: SiteErrorLog.py,v 1.10 2002/08/14 22:25:11 mj Exp $
"""
import os
......@@ -46,7 +46,7 @@ log_to_event_log = 'Log to the Event Log'
_rate_restrict_pool = {}
# The number of seconds that must elapse on average between sending two
# exceptions of the same name into the the Event Log. one per minute.
# exceptions of the same name into the the Event Log. one per minute.
_rate_restrict_period = 60
# The number of exceptions to allow in a burst before the above limit
......@@ -136,7 +136,7 @@ class SiteErrorLog (SimpleItem):
strtype = str(getattr(info[0], '__name__', info[0]))
if strtype in self._ignored_exceptions:
return
if not isinstance(info[2], StringType) and not isinstance(
info[2], UnicodeType):
tb_text = ''.join(
......@@ -227,7 +227,7 @@ class SiteErrorLog (SimpleItem):
RESPONSE.redirect(
'%s/manage_main?manage_tabs_message=Changed+properties.' %
self.absolute_url())
security.declareProtected(use_error_logging, 'getLogEntries')
def getLogEntries(self):
"""Returns the entries in the log.
......@@ -272,4 +272,3 @@ def manage_addErrorLog(dispatcher, RESPONSE=None):
RESPONSE.redirect(
dispatcher.DestinationURL() +
'/manage_main?manage_tabs_message=Error+Log+Added.' )
......@@ -2,18 +2,18 @@
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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.
#
#
##############################################################################
"""Site error log product.
$Id: __init__.py,v 1.2 2002/04/03 20:43:55 shane Exp $
$Id: __init__.py,v 1.3 2002/08/14 22:25:11 mj Exp $
"""
import SiteErrorLog
......@@ -23,4 +23,3 @@ def initialize(context):
constructors=(SiteErrorLog.manage_addErrorLog,),
permission=SiteErrorLog.use_error_logging,
icon='www/error.gif')
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
'''
Accelerated HTTP cache manager --
......@@ -138,7 +138,7 @@ class AcceleratedHTTPCacheManager (CacheManager, SimpleItem):
def getId(self):
' '
return self.id
ZCacheManager_getCache__roles__ = ()
def ZCacheManager_getCache(self):
cacheid = self.__cacheid
......@@ -181,7 +181,7 @@ class AcceleratedHTTPCacheManager (CacheManager, SimpleItem):
req = self.REQUEST
sort_by = req.get('sort_by', 'anon')
sort_reverse = int(req.get('sort_reverse', 1))
return sort_by, sort_reverse
return sort_by, sort_reverse
def getCacheReport(self):
"""
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
'''
RAM cache manager --
......@@ -145,7 +145,7 @@ class RAMCache (Cache):
else:
return None
return oc
def countAllEntries(self):
'''
Returns the count of all cache entries.
......@@ -296,7 +296,7 @@ class RAMCache (Cache):
oc.hits = oc.hits + 1
entry.access_count = entry.access_count + 1
return entry.data
def ZCache_set(self, ob, data, view_name='', keywords=None,
mtime_func=None):
'''
......@@ -356,7 +356,7 @@ class RAMCacheManager (CacheManager, SimpleItem):
def getId(self):
' '
return self.id
ZCacheManager_getCache__roles__ = ()
def ZCacheManager_getCache(self):
cacheid = self.__cacheid
......@@ -406,7 +406,7 @@ class RAMCacheManager (CacheManager, SimpleItem):
req = self.REQUEST
sort_by = req.get('sort_by', 'hits')
sort_reverse = int(req.get('sort_reverse', 1))
return sort_by, sort_reverse
return sort_by, sort_reverse
def getCacheReport(self):
"""
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
'''
Some standard Zope cache managers from Digital Creations.
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
from ZODB.Connection import Connection
......@@ -43,5 +43,3 @@ class LowConflictConnection(Connection):
d=object.__dict__
for k,v in state.items(): d[k]=v
object._p_serial=serial
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""
Mounted database support
......@@ -22,9 +22,9 @@ lives in another ZODB.
To understand this fully, you'll need to read the source of
ZODB.Mount.MountPoint.
$Id: TemporaryFolder.py,v 1.6 2002/08/12 21:14:15 chrism Exp $
$Id: TemporaryFolder.py,v 1.7 2002/08/14 22:25:13 mj Exp $
"""
__version__='$Revision: 1.6 $'[11:-2]
__version__='$Revision: 1.7 $'[11:-2]
import Globals
from Globals import HTMLFile
......@@ -38,7 +38,7 @@ from LowConflictConnection import LowConflictConnection
ADD_TEMPORARY_FOLDER_PERM="Add Temporary Folder"
def constructTemporaryFolder(self, id, title=None, REQUEST=None):
""" """
ms = MountedTemporaryFolder(id, title)
......@@ -58,7 +58,7 @@ class MountedTemporaryFolder(MountPoint, OFS.SimpleItem.Item):
icon = 'p_/broken'
manage_options = ({'label':'Traceback', 'action':'manage_traceback'},)
meta_type = 'Broken Temporary Folder'
def __init__(self, id, title='', params=None):
self.id = str(id)
self.title = title
......@@ -71,7 +71,7 @@ class MountedTemporaryFolder(MountPoint, OFS.SimpleItem.Item):
db = DB(TemporaryStorage())
db.klass = LowConflictConnection
return db
def _getMountRoot(self, root):
sdc = root.get('folder', None)
if sdc is None:
......@@ -79,7 +79,7 @@ class MountedTemporaryFolder(MountPoint, OFS.SimpleItem.Item):
self._populate(sdc, root)
return sdc
def mount_error_(self):
return self._v_connect_error
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""
......@@ -17,10 +17,10 @@ MappingStorage. Unlike MappingStorage, it needs not be packed to get rid of
non-cyclic garbage and it does rudimentary conflict resolution. This is a
ripoff of Jim's Packless bsddb3 storage.
$Id: TemporaryStorage.py,v 1.9 2002/06/30 18:23:15 chrism Exp $
$Id: TemporaryStorage.py,v 1.10 2002/08/14 22:25:13 mj Exp $
"""
__version__ ='$Revision: 1.9 $'[11:-2]
__version__ ='$Revision: 1.10 $'[11:-2]
from zLOG import LOG, BLATHER
from ZODB.referencesf import referencesf
......@@ -82,12 +82,12 @@ class TemporaryStorage(BaseStorage, ConflictResolvingStorage):
del self._conflict_cache[k]
self._last_cache_gc = now
self._tmp = []
def close(self):
"""
Close the storage
"""
def load(self, oid, version):
self._lock_acquire()
try:
......@@ -112,7 +112,7 @@ class TemporaryStorage(BaseStorage, ConflictResolvingStorage):
return data[0] # data here is actually (data, t)
finally:
self._lock_release()
def store(self, oid, serial, data, version, transaction):
if transaction is not self._transaction:
raise POSException.StorageTransactionError(self, transaction)
......@@ -217,7 +217,7 @@ class TemporaryStorage(BaseStorage, ConflictResolvingStorage):
self._takeOutGarbage(oid)
self._tmp = []
def _takeOutGarbage(self, oid):
# take out the garbage.
referenceCount=self._referenceCount
......@@ -246,7 +246,7 @@ class TemporaryStorage(BaseStorage, ConflictResolvingStorage):
referenceCount[roid] = rc - 1
try: del self._oreferences[oid]
except: pass
def pack(self, t, referencesf):
self._lock_acquire()
try:
......@@ -268,9 +268,3 @@ class TemporaryStorage(BaseStorage, ConflictResolvingStorage):
self._takeOutGarbage(oid)
finally:
self._lock_release()
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""
Temporary Folder initialization routines
$Id: __init__.py,v 1.5 2002/01/11 14:53:38 chrism Exp $
$Id: __init__.py,v 1.6 2002/08/14 22:25:13 mj Exp $
"""
import ZODB # for testrunner to be happy
......
# Utility program to patch Data.fs.in to include a temporary folder, browser
# id manager, and session data manager
############################################################################
#
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
......@@ -18,7 +18,7 @@ import Globals
from ZODB import FileStorage, DB
import Products.Sessions.BrowserIdManager
import Products.Sessions.SessionDataManager
import Products.TemporaryFolder.TemporaryFolder
import Products.TemporaryFolder.TemporaryFolder
import os.path
import sys
......
import ZODB
from ZODB.tests.MinPO import MinPO
from Products.TemporaryFolder import TemporaryStorage
......@@ -47,7 +46,7 @@ class TemporaryStorageTests(
oid4 = self._storage.new_oid()
self._dostore(oid4, data=MinPO(11))
assert len(self._storage._conflict_cache) == 1
finally:
TemporaryStorage.CONFLICT_CACHE_GCEVERY = old_gcevery
TemporaryStorage.CONFLICT_CACHE_MAXAGE = old_maxage
......@@ -64,14 +63,14 @@ def main():
runner.run(alltests)
def debug():
test_suite().debug()
test_suite().debug()
def pdebug():
import pdb
pdb.run('debug()')
if __name__=='__main__':
if len(sys.argv) > 1:
globals()[sys.argv[1]]()
else:
main()
if len(sys.argv) > 1:
globals()[sys.argv[1]]()
else:
main()
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""
Transient Object Container Class ('timeslice'-based design).
$Id: Transience.py,v 1.27 2002/08/07 14:48:48 chrism Exp $
$Id: Transience.py,v 1.28 2002/08/14 22:25:13 mj Exp $
"""
__version__='$Revision: 1.27 $'[11:-2]
__version__='$Revision: 1.28 $'[11:-2]
import Globals
from Globals import HTMLFile
......@@ -127,7 +127,7 @@ class TransientObjectContainer(SimpleItem):
{ 'label': 'Manage',
'action': 'manage_container',
'help': ('Transience', 'Transience.stx')
},
},
{ 'label': 'Security',
'action': 'manage_access'
},
......@@ -229,7 +229,7 @@ class TransientObjectContainer(SimpleItem):
def setAddNotificationTarget(self, f):
# We should assert that the callback function 'f' implements
# the TransientNotification interface
self._addCallback = f
self._addCallback = f
security.declareProtected(MGMT_SCREEN_PERM, 'getDelNotificationTarget')
def getDelNotificationTarget(self):
......@@ -252,7 +252,7 @@ class TransientObjectContainer(SimpleItem):
def _notify(self, items, kind):
if not type(items) in [type([]), type(())]:
items = [items]
if kind =='add':
name = 'notifyAdd'
callback = self._addCallback
......@@ -437,7 +437,7 @@ class TransientObjectContainer(SimpleItem):
self._deindex_next=Increaser(self._getCurrentTimeslice())
finally:
self.lock.release()
def _getCurrentBucket(self):
"""
Do housekeeping if necessary, then return the 'current' bucket.
......@@ -673,7 +673,7 @@ class TransientObjectContainer(SimpleItem):
data[i] = OOBTree()
except Queue.Empty:
DEBUG and TLOG('replentish queue empty')
# gc the stale buckets at the "beginning" of _data ("garbage collect")
# iterate over the keys in data that have no minimum value and
# a maximum value of delete_end (note: ordered set)
......@@ -741,7 +741,7 @@ class TransientObjectContainer(SimpleItem):
finally:
self.lock.release()
def __getitem__(self, k):
self.lock.acquire()
try:
......@@ -803,7 +803,7 @@ class TransientObjectContainer(SimpleItem):
# we accessed the object, so it becomes current
# by moving it to the current bucket
del self._data[b][k] # delete the item from the old bucket.
self._data[current][k] = v # add the value to the current
self._data[current][k] = v # add the value to the current
self._setLastAccessed(v)
index[k] = current # change the index to the current buck.
......@@ -812,7 +812,7 @@ class TransientObjectContainer(SimpleItem):
return v
finally:
self.lock.release()
def _setLastAccessed(self, transientObject):
self.lock.acquire()
try:
......@@ -860,7 +860,7 @@ class Increaser(Persistent):
def set(self, v):
self.value = v
def __getstate__(self):
return self.value
......
##########################################################################
##########################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
......@@ -9,7 +9,7 @@
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##########################################################################
##########################################################################
"""
Transient Objects
......@@ -66,7 +66,7 @@ Transient Objects
class Foo(Persistence.Persistent):
pass
transient_object = transient_data_container.new('t')
foo = transient_object['foo'] = Foo()
foo.bar = 1
......@@ -270,7 +270,7 @@ class StringKeyedHomogeneousItemContainer(HomogeneousItemContainer):
Returned object is acquisition-wrapped in self.
"""
class TransientItemContainer(Interface.Base):
def setTimeoutMinutes(timeout_mins):
"""
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""
Simple ZODB-based transient object implementation.
$Id: TransientObject.py,v 1.8 2002/06/24 19:31:16 chrism Exp $
$Id: TransientObject.py,v 1.9 2002/08/14 22:25:13 mj Exp $
"""
__version__='$Revision: 1.8 $'[11:-2]
__version__='$Revision: 1.9 $'[11:-2]
from Persistence import Persistent
from Acquisition import Implicit
......@@ -114,7 +114,7 @@ class TransientObject(Persistent, Implicit):
def getContainerKey(self):
return self.token
# -----------------------------------------------------------------
# DictionaryLike
#
......@@ -132,7 +132,7 @@ class TransientObject(Persistent, Implicit):
v = self._container.get(k, default)
if v is _notfound: return None
return v
def has_key(self, k):
if self._container.get(k, _notfound) is not _notfound: return 1
return 0
......@@ -243,7 +243,7 @@ class TransientObject(Persistent, Implicit):
'Conflict resolution error in TransientObject', '',
sys.exc_info()
)
getName = getId # this is for SQLSession compatibility
def _generateUniqueId(self):
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""
Transience initialization routines
$Id: __init__.py,v 1.6 2001/11/28 15:51:09 matt Exp $
$Id: __init__.py,v 1.7 2002/08/14 22:25:13 mj Exp $
"""
import ZODB # this is to help out testrunner, don't remove.
......@@ -21,7 +21,7 @@ import Transience
# import of MaxTransientObjectsExceeded for easy import from scripts,
# this is protected by a module security info declaration in the
# Sessions package.
from Transience import MaxTransientObjectsExceeded
from Transience import MaxTransientObjectsExceeded
def initialize(context):
context.registerClass(
......@@ -33,4 +33,3 @@ def initialize(context):
)
context.registerHelp()
context.registerHelpTitle('Zope Help')
##########################################################################
##########################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
......@@ -9,7 +9,7 @@
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##########################################################################
##########################################################################
"""
Transient Objects
......@@ -24,7 +24,7 @@ class TransientObjectContainer:
container. You'll almost always deal with a TransientObject
itself which you'll usually get as 'REQUEST.SESSION'.
"""
def getId(self):
"""
Returns a meaningful unique id for the object.
......@@ -79,7 +79,7 @@ class TransientObjectContainer:
Permission -- 'Create Transient Objects'
"""
def setTimeoutMinutes(self, timeout_mins):
"""
Set the number of minutes of inactivity allowable for subobjects
......@@ -182,7 +182,7 @@ class TransientObject:
Permission -- Always available
"""
def invalidate(self):
"""
Invalidate (expire) the transient object.
......@@ -291,5 +291,3 @@ class MaxTransientObjectsExceeded:
from Products.Transience import MaxTransientObjectsExceeded
"""
......@@ -9,4 +9,3 @@ def time():
def sleep(duration):
""" False sleep -- sleep for 1/10 the time specifed """
origtime.sleep(duration / 10.0)
......@@ -72,7 +72,7 @@ class TestBase(TestCase):
del self.app
Products.Transience.Transience.time = oldtime
Products.Transience.TransientObject.time = oldtime
class TestLastAccessed(TestBase):
def testLastAccessed(self):
sdo = self.app.sm.new_or_existing('TempObject')
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
import sys, os, unittest
......@@ -34,7 +34,7 @@ class TestTransientObject(TestCase):
Products.Transience.TransientObject.time = oldtime
self.t = None
del self.t
def test_id(self):
t = self.t.new('xyzzy')
assert t.getId() != 'xyzzy'
......@@ -99,10 +99,10 @@ class TestTransientObject(TestCase):
assert t.get('foobie') is None
self.assertRaises(AttributeError, self._genLenError, t)
assert t.get('foobie',None) is None
assert t.has_key('a')
assert not t.has_key('foobie')
assert t.has_key('a')
assert not t.has_key('foobie')
t.clear()
assert not len(t.keys())
assert not len(t.keys())
def test_TTWDictionary(self):
t = self.t.new('mouthfultest')
......@@ -111,7 +111,7 @@ class TestTransientObject(TestCase):
assert t.get('foo') == 'bar'
t.set('foobie', 'blech')
t.delete('foobie')
assert t.get('foobie') is None
assert t.get('foobie') is None
def test_suite():
......@@ -130,4 +130,3 @@ data = {
if __name__ == '__main__':
runner = TextTestRunner(verbosity=9)
runner.run(test_suite())
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
import sys, os, time, random, unittest
......@@ -75,7 +75,7 @@ class TestTransientObjectContainer(TestBase):
for x in v:
assert x == i
i = i + 1
def testKeysWorks(self):
for x in range(10, 110):
self.t[x] = x
......@@ -137,7 +137,7 @@ class TestTransientObjectContainer(TestBase):
self.t[4] = 99
del self.t[2]
assert lsubtract(self.t.keys(),[1,3,4,5,6,10])==[], `self.t.keys()`
def donttestDeleteTwoChildrenInorderSuccessorWorks(self):
self.t[5] = 6
self.t[2] = 10
......@@ -325,7 +325,7 @@ class TestTransientObjectContainer(TestBase):
# we should still have 100 - 199
for x in range(110, 210):
assert self.t[x] == x
# but we shouldn't have 0 - 100
# but we shouldn't have 0 - 100
for x in range(10, 110):
try: self.t[x]
except KeyError: pass
......@@ -439,13 +439,13 @@ class TestTransientObjectContainer(TestBase):
for x in range(11):
self.t.new(str(x))
def lsubtract(l1, l2):
l1=list(l1)
l2=list(l2)
l = filter(lambda x, l1=l1: x not in l1, l2)
l = l + filter(lambda x, l2=l2: x not in l2, l1)
return l
l1=list(l1)
l2=list(l2)
l = filter(lambda x, l1=l1: x not in l1, l2)
l = l + filter(lambda x, l2=l2: x not in l2, l1)
return l
def test_suite():
testsuite = makeSuite(TestTransientObjectContainer, 'test')
......@@ -456,4 +456,3 @@ def test_suite():
if __name__ == '__main__':
runner = TextTestRunner(verbosity=9)
runner.run(test_suite())
......@@ -81,10 +81,10 @@ class BaseIndex(Persistent):
# docid -> WidCode'd list of wids
# Used for un-indexing, and for phrase search.
self._docwords = IOBTree()
# Use a BTree length for efficient length computation w/o conflicts
self.length = BTrees.Length.Length()
def length(self):
"""Return the number of words in the index."""
# This is overridden per instance
......@@ -155,7 +155,7 @@ class BaseIndex(Persistent):
# The wid->weight mappings are fed into _add_wordinfo, and docweight
# becomes the value of _docweight[docid].
raise NotImplementedError
def has_doc(self, docid):
return self._docwords.has_key(docid)
......@@ -281,7 +281,7 @@ class BaseIndex(Persistent):
doc2score[docid] = weight
self._wordinfo[wid] = doc2score # not redundant: Persistency!
self.length.change(new_word_count)
def _del_wordinfo(self, wid, docid):
doc2score = self._wordinfo[wid]
......
......@@ -66,6 +66,6 @@ class IIndex(Interface.Base):
def unindex_doc(docid):
"XXX"
def has_doc(docid):
"""Returns true if docid is an id of a document in the index"""
......@@ -56,7 +56,7 @@ class ZCTextIndex(Persistent, Acquisition.Implicit, SimpleItem):
)
query_options = ['query']
security = ClassSecurityInfo()
security.declareObjectProtected(manage_zcatalog_indexes)
......@@ -65,11 +65,11 @@ class ZCTextIndex(Persistent, Acquisition.Implicit, SimpleItem):
def __init__(self, id, extra=None, caller=None, index_factory=None,
field_name=None, lexicon_id=None):
self.id = id
# Arguments can be passed directly to the constructor or
# via the silly "extra" record.
self._fieldname = field_name or getattr(extra, 'doc_attr', '') or id
lexicon_id = lexicon_id or extra.lexicon_idp
lexicon = getattr(caller, lexicon_id, None)
......@@ -94,11 +94,11 @@ class ZCTextIndex(Persistent, Acquisition.Implicit, SimpleItem):
self._index_factory = index_factory
self.index = self._index_factory(self.getLexicon())
## Private Methods ##
security.declarePrivate('getLexicon')
def getLexicon(self):
"""Get the lexicon for this index
"""
......@@ -108,7 +108,7 @@ class ZCTextIndex(Persistent, Acquisition.Implicit, SimpleItem):
lexicon = getattr(self.aq_parent, self.lexicon.getId())
self.lexicon_path = lexicon.getPhysicalPath()
del self.lexicon
try:
return self._v_lexicon
except AttributeError:
......@@ -122,7 +122,7 @@ class ZCTextIndex(Persistent, Acquisition.Implicit, SimpleItem):
## External methods not in the Pluggable Index API ##
security.declareProtected('query', search_zcatalog)
def query(self, query, nbest=10):
"""Return pair (mapping from docids to scores, num results).
......@@ -196,8 +196,8 @@ class ZCTextIndex(Persistent, Acquisition.Implicit, SimpleItem):
"""reinitialize the index (but not the lexicon)"""
try:
# Remove the cached reference to the lexicon
# So that it is refreshed
del self._v_lexicon
# So that it is refreshed
del self._v_lexicon
except (AttributeError, KeyError):
pass
self.index = self._index_factory(self.getLexicon())
......@@ -209,11 +209,11 @@ class ZCTextIndex(Persistent, Acquisition.Implicit, SimpleItem):
def getIndexType(self):
"""Return index type string"""
return getattr(self, '_index_type', self._index_factory.__name__)
def getFieldName(self):
"""Return indexed attribute name"""
return self._fieldname
def getLexiconPath(self):
"""Return the path of the lexicon used by the index"""
try:
......@@ -268,7 +268,7 @@ class PLexicon(Lexicon, Acquisition.Implicit, SimpleItem):
manage_options = ({'label':'Overview', 'action':'manage_main'},
{'label':'Query', 'action':'queryLexicon'},
) + SimpleItem.manage_options
security = ClassSecurityInfo()
security.declareObjectProtected(LexiconQueryPerm)
......@@ -282,11 +282,11 @@ class PLexicon(Lexicon, Acquisition.Implicit, SimpleItem):
def getPipelineNames(self):
"""Return list of names of pipeline element classes"""
return [element.__class__.__name__ for element in self._pipeline]
_queryLexicon = DTMLFile('dtml/queryLexicon', globals())
security.declareProtected(LexiconQueryPerm, 'queryLexicon')
def queryLexicon(self, REQUEST, words=None, page=0, rows=20, cols=4):
"""Lexicon browser/query user interface
"""
......@@ -297,7 +297,7 @@ class PLexicon(Lexicon, Acquisition.Implicit, SimpleItem):
words = [self.get_word(wid) for wid in wids]
else:
words = self.words()
word_count = len(words)
rows = max(min(rows, 500), 1)
cols = max(min(cols, 12), 1)
......@@ -306,18 +306,18 @@ class PLexicon(Lexicon, Acquisition.Implicit, SimpleItem):
page = max(min(page, page_count - 1), 0)
start = rows * cols * page
end = min(rows * cols * (page + 1), word_count)
if word_count:
words = list(words[start:end])
else:
words = []
columns = []
i = 0
while i < len(words):
columns.append(words[i:i + rows])
i += rows
return self._queryLexicon(self, REQUEST,
page=page,
rows=rows,
......@@ -328,8 +328,8 @@ class PLexicon(Lexicon, Acquisition.Implicit, SimpleItem):
page_count=page_count,
page_range=xrange(page_count),
page_columns=columns)
security.declareProtected(LexiconMgmtPerm, 'manage_main')
security.declareProtected(LexiconMgmtPerm, 'manage_main')
manage_main = DTMLFile('dtml/manageLexicon', globals())
InitializeClass(PLexicon)
......@@ -41,10 +41,10 @@ class Indexable:
class LexiconHolder(Acquisition.Implicit):
def __init__(self, lexicon):
self.lexicon = lexicon
def getPhysicalPath(self):
return ('',) # Pretend to be the root
def dummyUnrestrictedTraverse(self, path):
if path == ('', 'lexicon',):
return self.lexicon
......@@ -102,13 +102,13 @@ class ZCIndexTestsBase:
def setUp(self):
self.lexicon = PLexicon('lexicon', '',
Splitter(),
CaseNormalizer(),
Splitter(),
CaseNormalizer(),
StopWordRemover())
caller = LexiconHolder(self.lexicon)
self.zc_index = ZCTextIndex('name',
None,
caller,
self.zc_index = ZCTextIndex('name',
None,
caller,
self.IndexFactory,
'text',
'lexicon')
......@@ -466,14 +466,14 @@ class QueryTestsBase(testQueryEngine.TestQueryEngine,
def setUp(self):
self.lexicon = PLexicon('lexicon', '',
Splitter(),
CaseNormalizer(),
Splitter(),
CaseNormalizer(),
StopWordRemover())
caller = LexiconHolder(self.lexicon)
self.zc_index = ZCTextIndex('name',
None,
caller,
self.zc_index = ZCTextIndex('name',
None,
caller,
self.IndexFactory,
'text',
'lexicon')
......
This diff is collapsed.
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""ZCatalog Findable class
......@@ -28,7 +28,7 @@ class CatalogAware:
it is added or copied in Zope. If you make changes to your own
object, you are responsible for calling your object's index_object
method. """
meta_type='CatalogAware'
default_catalog='Catalog'
......@@ -40,7 +40,7 @@ class CatalogAware:
message = "Your changes have been saved"
if REQUEST is not None:
return self.manage_main(self, REQUEST, manage_tabs_message=message)
def manage_afterAdd(self, item, container):
self.index_object()
......@@ -135,12 +135,3 @@ class CatalogAware:
for item in obj.objectValues():
self.reindex_all(self, item)
return 'done!'
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
__version__ = "$Revision$"[11:-2]
......@@ -28,7 +28,7 @@ class AbstractCatalogBrain(Record.Record, Acquisition.Implicit):
def getPath(self):
"""Get the physical path for this record"""
return self.aq_parent.getpath(self.data_record_id_)
def getURL(self):
"""Try to generate a URL for this record"""
try:
......@@ -49,11 +49,11 @@ class AbstractCatalogBrain(Record.Record, Acquisition.Implicit):
zLOG.LOG('CatalogBrains', zLOG.INFO, 'getObject raised an error',
error=sys.exc_info())
pass
def getRID(self):
"""Return the record ID for this object."""
return self.data_record_id_
class NoBrainer:
""" This is an empty class to use when no brain is specified. """
pass
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""ZCatalog Findable class"""
......@@ -25,7 +25,7 @@ class CatalogAware:
it is added or copied in Zope. If you make changes to your own
object, you are responsible for calling your object's index_object
method. """
meta_type='CatalogAware'
default_catalog='Catalog'
......@@ -37,7 +37,7 @@ class CatalogAware:
message = "Your changes have been saved"
if REQUEST is not None:
return self.manage_main(self, REQUEST, manage_tabs_message=message)
def manage_afterAdd(self, item, container):
self.index_object()
......@@ -81,7 +81,7 @@ class CatalogAware:
def getPath(self):
"""Return the physical path for an object."""
return '/'.join(self.getPhysicalPath())
def summary(self, num=200):
"""Return a summary of the text content of the object."""
if not hasattr(self, 'text_content'):
......@@ -133,11 +133,3 @@ class CatalogPathAware(CatalogAware):
nontrivial, we don't want to spend a lot of time on ZClasses, and
this works.
"""
......@@ -2,17 +2,17 @@
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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.
#
#
##############################################################################
"""
$Id: IZCatalog.py,v 1.2 2002/08/14 19:10:14 caseman Exp $
$Id: IZCatalog.py,v 1.3 2002/08/14 22:25:15 mj Exp $
"""
from Interface import Interface
......@@ -35,20 +35,20 @@ class IZCatalog(Interface):
Keyword -- Keyword indexes index sequences of values. The index
can be used to search for objects that match one or more of the
search terms.
Path -- Path indexes index URI paths. They allow you to find objects
based on their placement in a hierarchy.
Date -- Date indexes index date and type data. They are a type of field
index specifically optimized for indexing dates.
Date Range -- Date range indexes index time intervals. They are designed
for efficient searching of dates falling between two boundaries
(such as effective / expiration dates).
Topic -- Topic indexes store prefiltered sets of documents. They are used
to optimize complex queries into a single fast query by prefiltering
documents by an expression
to optimize complex queries into a single fast query by prefiltering
documents by an expression
The ZCatalog can maintain a table of extra data about cataloged
objects. This information can be used on search result pages to
......@@ -61,7 +61,7 @@ class IZCatalog(Interface):
ZCatalog does not store references to the objects themselves, but
rather to a unique identifier that defines how to get to the
object. In Zope, this unique identifier is the object's relative
path to the ZCatalog (since two Zope objects cannot have the same
path to the ZCatalog (since two Zope objects cannot have the same
URL, this is an excellent unique qualifier in Zope).
"""
......@@ -108,11 +108,11 @@ class IZCatalog(Interface):
def index_objects():
"""Returns a sequence of actual index objects.
NOTE: This returns unwrapped indexes! You should probably use
getIndexObjects instead. Some indexes expect to be wrapped.
"""
def getIndexObjects():
"""Returns a list of acquisition wrapped index objects
"""
......@@ -184,7 +184,7 @@ class IZCatalog(Interface):
documented in The Zope Book.
"""
def __call__(REQUEST=None, **kw):
"""Search the catalog, the same way as 'searchResults'.
"""
......
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
__doc__='''$Id: Lazy.py,v 1.6 2001/11/28 15:51:09 matt Exp $'''
__version__='$Revision: 1.6 $'[11:-2]
__doc__='''$Id: Lazy.py,v 1.7 2002/08/14 22:25:15 mj Exp $'''
__version__='$Revision: 1.7 $'[11:-2]
class Lazy:
......@@ -20,7 +20,7 @@ class Lazy:
__allow_access_to_unprotected_subobjects__=1
def __repr__(self): return `list(self)`
def __len__(self):
try: return self._len
......@@ -62,7 +62,7 @@ class Lazy:
seq.append(other)
return LazyCat(seq)
def __getslice__(self,i1,i2):
r=[]
for i in xrange(i1,i2):
......@@ -75,7 +75,7 @@ class Lazy:
class LazyCat(Lazy):
# Lazy concatenation of one or more sequences. Should be handy
# for accessing small parts of big searches.
def __init__(self, sequences, length=None):
self._seq=sequences
self._data=[]
......
This diff is collapsed.
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""$Id: ZCatalogIndexes.py,v 1.7 2002/06/28 17:25:23 caseman Exp $
"""$Id: ZCatalogIndexes.py,v 1.8 2002/08/14 22:25:15 mj Exp $
"""
from Globals import DTMLFile, InitializeClass
......@@ -42,19 +42,19 @@ class ZCatalogIndexes (IFAwareObjectManager, Folder, Persistent, Implicit):
meta_type = "ZCatalogIndex"
manage_options = ()
security = ClassSecurityInfo()
security.declareObjectProtected(manage_zcatalog_indexes)
security.setPermissionDefault(manage_zcatalog_indexes, ('Manager',))
security.declareProtected(manage_zcatalog_indexes, 'addIndexForm')
addIndexForm= DTMLFile('dtml/addIndexForm',globals())
# You no longer manage the Indexes here, they are managed from ZCatalog
def manage_main(self, REQUEST, RESPONSE):
"""Redirect to the parent where the management screen now lives"""
RESPONSE.redirect('../manage_catalogIndexes')
manage_workspace = manage_main
#
......@@ -62,7 +62,7 @@ class ZCatalogIndexes (IFAwareObjectManager, Folder, Persistent, Implicit):
#
# base accessors loop back through our dictionary interface
def _setOb(self, id, object):
def _setOb(self, id, object):
indexes = self.aq_parent._catalog.indexes
indexes[id] = object
self.aq_parent._indexes = indexes
......@@ -74,14 +74,14 @@ class ZCatalogIndexes (IFAwareObjectManager, Folder, Persistent, Implicit):
self.aq_parent._indexes = indexes
#self.aq_parent._p_changed = 1
def _getOb(self, id, default=_marker):
def _getOb(self, id, default=_marker):
indexes = self.aq_parent._catalog.indexes
if default is _marker: return indexes.get(id)
return indexes.get(id, default)
security.declareProtected(manage_zcatalog_indexes, 'objectIds')
def objectIds(self, spec=None):
indexes = self.aq_parent._catalog.indexes
if spec is not None:
if type(spec) == type('s'):
......@@ -121,15 +121,13 @@ InitializeClass(ZCatalogIndexes)
class OldCatalogWrapperObject(SimpleItem, Implicit):
manage_options= (
{'label': 'Settings',
{'label': 'Settings',
'action': 'manage_main'},
)
manage_main = DTMLFile('dtml/manageOldindex',globals())
manage_main._setName('manage_main')
manage_workspace = manage_main
def __init__(self, o):
self.index = o
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
"""ZCatalog product"""
......@@ -26,7 +26,7 @@ createZClassForBase( CatalogPathAwareness.CatalogPathAware, globals()
def initialize(context):
context.registerClass(
ZCatalog.ZCatalog,
ZCatalog.ZCatalog,
permission='Add ZCatalogs',
constructors=(ZCatalog.manage_addZCatalogForm,
ZCatalog.manage_addZCatalog),
......@@ -40,7 +40,6 @@ def initialize(context):
Vocabulary.manage_addVocabulary),
icon='www/Vocabulary.gif',
)
context.registerHelp()
context.registerHelpTitle('Zope Help')
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
def manage_addVocabulary(id, title, globbing=None, REQUEST=None):
"""
Add a Vocabulary object to an ObjectManager.
"""
......@@ -28,7 +28,7 @@ class Vocabulary:
A Vocabulary manages words and language rules for text indexing.
Text indexing is done by the ZCatalog and other third party
Products.
"""
__constructor__=manage_addVocabulary
......@@ -39,7 +39,7 @@ class Vocabulary:
Query Vocabulary for words matching pattern.
"""
def insert(word):
"""
......@@ -47,12 +47,10 @@ class Vocabulary:
Insert a word in the Vocabulary.
"""
def words():
"""
Return list of words.
"""
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (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
#
#
##############################################################################
def manage_addZCatalog(id, title, vocab_id=None):
......@@ -43,20 +43,20 @@ class ZCatalog:
Keyword -- Keyword indexes index sequences of values. The index
can be used to search for objects that match one or more of the
search terms.
Path -- Path indexes index URI paths. They allow you to find objects
based on their placement in a hierarchy.
Date -- Date indexes index date and type data. They are a type of field
index specifically optimized for indexing dates.
Date Range -- Date range indexes index time intervals. They are designed
for efficient searching of dates falling between two boundaries
(such as effective / expiration dates).
Topic -- Topic indexes store prefiltered sets of documents. They are used
to optimize complex queries into a single fast query by prefiltering
documents by an expression
to optimize complex queries into a single fast query by prefiltering
documents by an expression
The ZCatalog can maintain a table of extra data about cataloged
objects. This information can be used on search result pages to
......@@ -69,7 +69,7 @@ class ZCatalog:
ZCatalog does not store references to the objects themselves, but
rather to a unique identifier that defines how to get to the
object. In Zope, this unique identifier is the object's relative
path to the ZCatalog (since two Zope objects cannot have the same
path to the ZCatalog (since two Zope objects cannot have the same
URL, this is an excellent unique qualifier in Zope).
"""
......@@ -99,18 +99,18 @@ class ZCatalog:
def getpath(rid):
"""
Return the path to a cataloged object given a
'data_record_id_'
"""
def getobject(rid, REQUEST=None):
"""
Return a cataloged object given a 'data_record_id_'
"""
def schema():
......@@ -123,24 +123,24 @@ class ZCatalog:
def index_objects():
"""
Returns a sequence of actual index objects.
NOTE: This returns unwrapped indexes! You should probably use
getIndexObjects instead. Some indexes expect to be wrapped.
"""
def getIndexObjects():
"""
Returns a list of acquisition wrapped index objects
"""
def searchResults(REQUEST=None, **kw):
"""
Search the catalog. Search terms can be passed in the REQUEST
or as keyword arguments.
......@@ -206,9 +206,8 @@ class ZCatalog:
documented in The Zope Book.
"""
def __call__(REQUEST=None, **kw):
"""
Search the catalog, the same way as 'searchResults'.
"""
......@@ -8,41 +8,39 @@ class Keywords:
def __init__(self):
self.kw = []
def build(self,mbox,limit):
mb = mailbox.UnixMailbox(open(mbox))
msg = mb.next()
while msg and len(self.kw) < limit:
sub = msg.dict.get("subject","").split(' ')
for f in sub:
ok = 1
for c in f:
for c in f:
if not c in string.letters: ok=0
if ok==1 and not f in self.kw : self.kw.append(f)
msg = mb.next()
P = cPickle.Pickler(open('data/keywords','w'))
P.dump(self.kw)
def reload(self):
P = cPickle.Unpickler(open('data/keywords','r'))
self.kw = P.load()
def keywords(self):
return self.kw
if __name__=="__main__":
k = Keywords()
k.build("/home/andreas/zope.mbox",1000)
......@@ -89,13 +89,13 @@ Commands:
3.41 (0, 1)
as described above.
pdebug command args
Run one of the other commands in the Python debugger.
sample suite of tests::
cd lib/python
python Products/ZCatalog/regressiontests/loadmail.py base ~/zope.mbox 1000
python Products/ZCatalog/regressiontests/loadmail.py index 100
......@@ -162,7 +162,7 @@ def loadmail(dest, name, mbox, printstat=0, max=-1):
dest.manage_addFolder(name)
else:
Products.BTreeFolder.BTreeFolder.manage_addBTreeFolder(dest, name)
dest=getattr(dest, name)
f=open(mbox)
mb=mailbox.UnixMailbox(f)
......@@ -186,7 +186,7 @@ def loadmail(dest, name, mbox, printstat=0, max=-1):
message=mb.next()
dest.number_of_messages=i
print
print
get_transaction().commit()
def loadinc(name, mb, printstat=0, max=99999999, wait=1):
......@@ -233,8 +233,8 @@ def loadinc(name, mb, printstat=0, max=99999999, wait=1):
doc=app=mdest=0
jar.close()
if printstat: sys.stdout.write("\t%s\t%s\t\n" % (i, f.tell()))
sys.stdout.flush()
return rconflicts, wconflicts
......@@ -259,7 +259,7 @@ def indexf(app):
r.PARENTS=[0, app.mail]
app.cat.manage_catalogFoundItems(r,r,'','',['DTML Document'])
get_transaction().commit()
def index():
os.environ['STUPID_LOG_FILE']=''
os.environ['STUPID_LOG_SEVERITY']='-111'
......@@ -276,16 +276,16 @@ def index():
import PLexicon
from Products.ZCTextIndex.Lexicon \
import Splitter, CaseNormalizer
app.cat._setObject('lex',
PLexicon('lex', '', Splitter(), CaseNormalizer())
)
class extra:
doc_attr = 'PrincipiaSearchSource'
lexicon_id = 'lex'
index_type = 'Okapi BM25 Rank'
app.cat.addIndex('PrincipiaSearchSource', 'ZCTextIndex', extra)
get_transaction().commit()
......@@ -377,7 +377,7 @@ def inc():
print t, c, size, mem
#hist("%s-%s-%s" % (omin, count, threads))
Zope.DB.close()
words=['banishment', 'indirectly', 'imprecise', 'peeks',
......@@ -608,7 +608,7 @@ def incedit(edits, wait, ndel=20, nins=20):
doc=app=0
jar.close()
return rconflicts, wconflicts
def edit():
......@@ -671,7 +671,7 @@ def edit():
print t, c, size, mem
#hist("e%s" % (threads))
Zope.DB.close()
def VmSize():
......
......@@ -37,15 +37,15 @@ class UnicodeTextIndexCatalogTest(unittest.TestCase):
t4 = TO('i am a brown ' + unicode('fox') + ' dancing with a future alien',[])
t5 = TO("""
Die USA und Grobritannien knnen nach der Zerstrung der
afghanischen Luftabwehr nun rund um die Uhr Angriffe fliegen. Das gab
afghanischen Luftabwehr nun rund um die Uhr Angriffe fliegen. Das gab
Verteidigungsminister Donald Rumsfeld bekannt. Bei den dreitgigen Angriffen
seien auch bis auf einen alle Flugpltze der Taliban zerstrt worden. Rumsfeld
erklrte weiter, er knne die Berichte nicht besttigen, wonach bei den
erklrte weiter, er knne die Berichte nicht besttigen, wonach bei den
amerikanischen Angriffen vier afghanische Mitarbeiter einer von den UN
finanzierten Hilfsorganisation gettet wurden. Diese knnten auch durch
Gegenfeuer der Taliban gettet worden sein.
""",[unicode('dreitgigen','latin1'),'zerstrt'])
self.cat.catalog_object(t1,"o1")
self.cat.catalog_object(t2,"o2")
......@@ -59,7 +59,7 @@ class UnicodeTextIndexCatalogTest(unittest.TestCase):
('dreitgigen',('o5',))
]
self.kw_tests = [ ('quick',('o1',) ),
('zerstrt',('o3','o5')),
('dreitgigen',('o5',))
......
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