[Checkins] SVN: Products.CMFDefault/trunk/Products/CMFDefault/ code cleanup:
Yvo Schubbe
cvs-admin at zope.org
Tue Apr 24 10:36:22 UTC 2012
Log message for revision 125266:
code cleanup:
- replaced has_key
- replaced oldstyle errors
- PEP 8
Changed:
U Products.CMFDefault/trunk/Products/CMFDefault/DiscussionItem.py
U Products.CMFDefault/trunk/Products/CMFDefault/MetadataTool.py
U Products.CMFDefault/trunk/Products/CMFDefault/browser/membership/authentication.py
U Products.CMFDefault/trunk/Products/CMFDefault/skins/zpt_control/personalize.py
U Products.CMFDefault/trunk/Products/CMFDefault/skins/zpt_generic/getBatchNavigation.py
U Products.CMFDefault/trunk/Products/CMFDefault/skins/zpt_generic/roster.pt
U Products.CMFDefault/trunk/Products/CMFDefault/tests/test_SyndicationInfo.py
U Products.CMFDefault/trunk/Products/CMFDefault/utils.py
-=-
Modified: Products.CMFDefault/trunk/Products/CMFDefault/DiscussionItem.py
===================================================================
--- Products.CMFDefault/trunk/Products/CMFDefault/DiscussionItem.py 2012-04-24 10:35:58 UTC (rev 125265)
+++ Products.CMFDefault/trunk/Products/CMFDefault/DiscussionItem.py 2012-04-24 10:36:19 UTC (rev 125266)
@@ -44,10 +44,10 @@
implements(IDiscussionResponse)
- meta_type = 'Discussion Item'
- portal_type = 'Discussion Item'
- allow_discussion = 1
- in_reply_to = None
+ meta_type = 'Discussion Item'
+ portal_type = 'Discussion Item'
+ allow_discussion = 1
+ in_reply_to = None
security = ClassSecurityInfo()
@@ -58,7 +58,7 @@
if not hasattr(aq_base(self), 'creators'):
# for content created with CMF versions before 1.5
if hasattr(aq_base(self), 'creator') and self.creator != 'unknown':
- self.creators = ( self.creator, )
+ self.creators = (self.creator,)
else:
self.creators = ()
return self.creators
@@ -67,7 +67,7 @@
# IDiscussionResponse interface
#
security.declareProtected(View, 'inReplyTo')
- def inReplyTo( self, REQUEST=None ):
+ def inReplyTo(self, REQUEST=None):
""" Return the IDiscussable object to which we are a reply.
Two cases obtain:
@@ -80,21 +80,21 @@
field will be the ID of the parent DiscussionItem.
"""
tool = getUtility(IDiscussionTool)
- talkback = tool.getDiscussionFor( self )
- return talkback._getReplyParent( self.in_reply_to )
+ talkback = tool.getDiscussionFor(self)
+ return talkback._getReplyParent(self.in_reply_to)
security.declarePrivate(View, 'setReplyTo')
- def setReplyTo( self, reply_to ):
+ def setReplyTo(self, reply_to):
"""
Make this object a response to the passed object.
"""
- if getattr( reply_to, 'meta_type', None ) == self.meta_type:
+ if getattr(reply_to, 'meta_type', None) == self.meta_type:
self.in_reply_to = reply_to.getId()
else:
self.in_reply_to = None
security.declareProtected(View, 'parentsInThread')
- def parentsInThread( self, size=0 ):
+ def parentsInThread(self, size=0):
"""
Return the list of items which are "above" this item in
the discussion thread.
@@ -104,19 +104,19 @@
"""
parents = []
current = self
- while not size or len( parents ) < size:
+ while not size or len(parents) < size:
parent = current.inReplyTo()
assert not parent in parents # sanity check
- parents.insert( 0, parent )
+ parents.insert(0, parent)
if parent.meta_type != self.meta_type:
break
current = parent
return parents
-InitializeClass( DiscussionItem )
+InitializeClass(DiscussionItem)
-class DiscussionItemContainer( Persistent, Implicit, Traversable ):
+class DiscussionItemContainer(Persistent, Implicit, Traversable):
"""
Store DiscussionItem objects. Discussable content that
@@ -137,16 +137,16 @@
self._container = PersistentMapping()
security.declareProtected(View, 'getId')
- def getId( self ):
+ def getId(self):
return self.id
security.declareProtected(View, 'getReply')
- def getReply( self, reply_id ):
+ def getReply(self, reply_id):
"""
Return a discussion item, given its ID; raise KeyError
if not found.
"""
- return self._container.get( reply_id ).__of__(self)
+ return self._container.get(reply_id).__of__(self)
# Is this right?
security.declareProtected(View, '__bobo_traverse__')
@@ -162,7 +162,7 @@
try:
return self.getReply(name)
except:
- parent = aq_parent( aq_inner( self ) )
+ parent = aq_parent(aq_inner(self))
if parent.getId() == name:
return parent
else:
@@ -187,7 +187,7 @@
for obj in self.objectValues():
obj.__of__(self).notifyWorkflowCreated()
- security.declarePrivate( 'manage_beforeDelete' )
+ security.declarePrivate('manage_beforeDelete')
def manage_beforeDelete(self, item, container):
"""
Remove the contained items from the catalog.
@@ -200,7 +200,7 @@
# OFS.ObjectManager query interface.
#
security.declareProtected(AccessContentsInformation, 'objectIds')
- def objectIds( self, spec=None ):
+ def objectIds(self, spec=None):
"""
Return a list of the ids of our DiscussionItems.
"""
@@ -208,20 +208,18 @@
return []
return self._container.keys()
-
security.declareProtected(AccessContentsInformation, 'objectItems')
def objectItems(self, spec=None):
"""
Return a list of (id, subobject) tuples for our DiscussionItems.
"""
- r=[]
- a=r.append
- g=self._container.get
+ r = []
+ a = r.append
+ g = self._container.get
for id in self.objectIds(spec):
- a( (id, g( id ) ) )
+ a((id, g(id)))
return r
-
security.declareProtected(AccessContentsInformation, 'objectValues')
def objectValues(self):
"""
@@ -233,18 +231,17 @@
# IDiscussable interface
#
security.declareProtected(ReplyToItem, 'createReply')
- def createReply( self, title, text, Creator=None, text_format='structured-text' ):
+ def createReply(self, title, text, Creator=None,
+ text_format='structured-text'):
"""
Create a reply in the proper place
"""
- container = self._container
-
id = int(DateTime().timeTime())
- while self._container.get( str(id), None ) is not None:
+ while self._container.get(str(id), None) is not None:
id = id + 1
- id = str( id )
+ id = str(id)
- item = DiscussionItem( id, title=title, description=title )
+ item = DiscussionItem(id, title=title, description=title)
self._container[id] = item
item = item.__of__(self)
@@ -259,45 +256,46 @@
return id
security.declareProtected(ManagePortal, 'deleteReply')
- def deleteReply( self, reply_id ):
+ def deleteReply(self, reply_id):
""" Remove a reply from this container """
- if self._container.has_key( reply_id ):
- reply = self._container.get( reply_id ).__of__( self )
+ if reply_id in self._container:
+ reply = self._container.get(reply_id).__of__(self)
my_replies = reply.talkback.getReplies()
for my_reply in my_replies:
my_reply_id = my_reply.getId()
self.deleteReply(my_reply_id)
- if hasattr( reply, 'unindexObject' ):
+ if hasattr(reply, 'unindexObject'):
reply.unindexObject()
del self._container[reply_id]
-
security.declareProtected(View, 'hasReplies')
- def hasReplies( self, content_obj ):
+ def hasReplies(self, content_obj):
"""
Test to see if there are any dicussion items
"""
- outer = self._getDiscussable( outer=1 )
+ outer = self._getDiscussable(outer=1)
if content_obj == outer:
- return bool( len(self._container) )
+ return bool(len(self._container))
else:
- return bool( len( content_obj.talkback._getReplyResults() ) )
+ return bool(len(content_obj.talkback._getReplyResults()))
security.declareProtected(View, 'replyCount')
- def replyCount( self, content_obj ):
+ def replyCount(self, content_obj):
""" How many replies do i have? """
- outer = self._getDiscussable( outer=1 )
+ outer = self._getDiscussable(outer=1)
if content_obj == outer:
- return len( self._container )
+ return len(self._container)
else:
replies = content_obj.talkback.getReplies()
- return self._repcount( replies )
+ return self._repcount(replies)
security.declarePrivate('_repcount')
- def _repcount( self, replies ):
- """ counts the total number of replies by recursing thru the various levels
+ def _repcount(self, replies):
+ """counts the total number of replies
+
+ by recursing thru the various levels
"""
count = 0
@@ -307,12 +305,12 @@
#if there is at least one reply to this reply
replies = reply.talkback.getReplies()
if replies:
- count = count + self._repcount( replies )
+ count = count + self._repcount(replies)
return count
security.declareProtected(View, 'getReplies')
- def getReplies( self ):
+ def getReplies(self):
""" Return a sequence of the IDiscussionResponse objects which are
associated with this Discussable
"""
@@ -321,7 +319,7 @@
result_ids = self._getReplyResults()
for id in result_ids:
- a( self._container.get( id ).__of__( self ) )
+ a(self._container.get(id).__of__(self))
return objects
@@ -337,33 +335,33 @@
#
# Utility methods
#
- security.declarePrivate( '_getReplyParent' )
- def _getReplyParent( self, in_reply_to ):
+ security.declarePrivate('_getReplyParent')
+ def _getReplyParent(self, in_reply_to):
"""
Return the object indicated by the 'in_reply_to', where
'None' represents the "outer" content object.
"""
- outer = self._getDiscussable( outer=1 )
+ outer = self._getDiscussable(outer=1)
if in_reply_to is None:
return outer
- parent = self._container[ in_reply_to ].__of__( aq_inner( self ) )
- return parent.__of__( outer )
+ parent = self._container[in_reply_to].__of__(aq_inner(self))
+ return parent.__of__(outer)
- security.declarePrivate( '_getDiscussable' )
- def _getDiscussable( self, outer=0 ):
+ security.declarePrivate('_getDiscussable')
+ def _getDiscussable(self, outer=0):
"""
"""
- tb = outer and aq_inner( self ) or self
- return getattr( tb, 'aq_parent', None )
+ tb = outer and aq_inner(self) or self
+ return getattr(tb, 'aq_parent', None)
- security.declarePrivate( '_getReplyResults' )
- def _getReplyResults( self ):
+ security.declarePrivate('_getReplyResults')
+ def _getReplyResults(self):
"""
Get a list of ids of DiscussionItems which are replies to
our Discussable.
"""
discussable = self._getDiscussable()
- outer = self._getDiscussable( outer=1 )
+ outer = self._getDiscussable(outer=1)
if discussable == outer:
in_reply_to = None
@@ -374,9 +372,9 @@
a = result.append
for key, value in self._container.items():
if value.in_reply_to == in_reply_to:
- a( ( key, value ) )
+ a((key, value))
- result.sort( lambda a, b: cmp(a[1].creation_date, b[1].creation_date) )
+ result.sort(lambda a, b: cmp(a[1].creation_date, b[1].creation_date))
return [ x[0] for x in result ]
Modified: Products.CMFDefault/trunk/Products/CMFDefault/MetadataTool.py
===================================================================
--- Products.CMFDefault/trunk/Products/CMFDefault/MetadataTool.py 2012-04-24 10:35:58 UTC (rev 125265)
+++ Products.CMFDefault/trunk/Products/CMFDefault/MetadataTool.py 2012-04-24 10:36:19 UTC (rev 125266)
@@ -31,7 +31,7 @@
from Products.CMFDefault.utils import _dtmldir
-class MetadataElementPolicy( SimpleItem ):
+class MetadataElementPolicy(SimpleItem):
""" Represent a type-specific policy about a particular metadata element.
"""
@@ -40,11 +40,11 @@
#
# Default values.
#
- is_required = 0
- supply_default = 0
- default_value = ''
- enforce_vocabulary = 0
- allowed_vocabulary = ()
+ is_required = 0
+ supply_default = 0
+ default_value = ''
+ enforce_vocabulary = 0
+ allowed_vocabulary = ()
def __init__(self, is_multi_valued=False):
self.is_multi_valued = bool(is_multi_valued)
@@ -52,65 +52,63 @@
#
# Mutator.
#
- security.declareProtected(ManagePortal , 'edit')
- def edit( self
- , is_required
- , supply_default
- , default_value
- , enforce_vocabulary
- , allowed_vocabulary
- ):
- self.is_required = bool(is_required)
- self.supply_default = bool(supply_default)
- self.default_value = default_value
+ security.declareProtected(ManagePortal, 'edit')
+ def edit(self,
+ is_required,
+ supply_default,
+ default_value,
+ enforce_vocabulary,
+ allowed_vocabulary):
+ self.is_required = bool(is_required)
+ self.supply_default = bool(supply_default)
+ self.default_value = default_value
self.enforce_vocabulary = bool(enforce_vocabulary)
self.allowed_vocabulary = tuple(allowed_vocabulary)
#
# Query interface
#
- security.declareProtected(View , 'isMultiValued')
- def isMultiValued( self ):
+ security.declareProtected(View, 'isMultiValued')
+ def isMultiValued(self):
""" Can this element hold multiple values?
"""
return self.is_multi_valued
- security.declareProtected(View , 'isRequired')
- def isRequired( self ):
+ security.declareProtected(View, 'isRequired')
+ def isRequired(self):
""" Must this element be supplied?
"""
return self.is_required
- security.declareProtected(View , 'supplyDefault')
- def supplyDefault( self ):
+ security.declareProtected(View, 'supplyDefault')
+ def supplyDefault(self):
""" Should the tool supply a default?
"""
return self.supply_default
- security.declareProtected(View , 'defaultValue')
- def defaultValue( self ):
+ security.declareProtected(View, 'defaultValue')
+ def defaultValue(self):
""" If so, what is the default?
"""
return self.default_value
- security.declareProtected(View , 'enforceVocabulary')
- def enforceVocabulary( self ):
+ security.declareProtected(View, 'enforceVocabulary')
+ def enforceVocabulary(self):
""" Should the tool enforce the policy's vocabulary?
"""
return self.enforce_vocabulary
- security.declareProtected(View , 'allowedVocabulary')
- def allowedVocabulary( self ):
+ security.declareProtected(View, 'allowedVocabulary')
+ def allowedVocabulary(self):
""" What are the allowed values?
"""
return self.allowed_vocabulary
-InitializeClass( MetadataElementPolicy )
+InitializeClass(MetadataElementPolicy)
+class ElementSpec(SimpleItem):
-class ElementSpec( SimpleItem ):
-
""" Represent all the tool knows about a single metadata element.
"""
@@ -121,35 +119,35 @@
#
is_multi_valued = 0
- def __init__( self, is_multi_valued ):
- self.is_multi_valued = is_multi_valued
- self.policies = PersistentMapping()
- self.policies[ None ] = self._makePolicy() # set default policy
+ def __init__(self, is_multi_valued):
+ self.is_multi_valued = is_multi_valued
+ self.policies = PersistentMapping()
+ self.policies[None] = self._makePolicy() # set default policy
- security.declarePrivate( '_makePolicy' )
- def _makePolicy( self ):
- return MetadataElementPolicy( self.is_multi_valued )
+ security.declarePrivate('_makePolicy')
+ def _makePolicy(self):
+ return MetadataElementPolicy(self.is_multi_valued)
- security.declareProtected(View , 'isMultiValued')
- def isMultiValued( self ):
+ security.declareProtected(View, 'isMultiValued')
+ def isMultiValued(self):
"""
Is this element multi-valued?
"""
return self.is_multi_valued
- security.declareProtected(View , 'getPolicy')
- def getPolicy( self, typ=None ):
+ security.declareProtected(View, 'getPolicy')
+ def getPolicy(self, typ=None):
""" Find the policy for this element for objects of the given type.
o Return a default, if none found.
"""
try:
- return self.policies[ typ ].__of__(self)
+ return self.policies[typ].__of__(self)
except KeyError:
- return self.policies[ None ].__of__(self)
+ return self.policies[None].__of__(self)
- security.declareProtected(View , 'listPolicies')
- def listPolicies( self ):
+ security.declareProtected(View, 'listPolicies')
+ def listPolicies(self):
""" Return a list of all policies for this element.
"""
res = []
@@ -157,32 +155,32 @@
res.append((k, v.__of__(self)))
return res
- security.declareProtected(ManagePortal , 'addPolicy')
- def addPolicy( self, typ ):
+ security.declareProtected(ManagePortal, 'addPolicy')
+ def addPolicy(self, typ):
""" Add a policy to this element for objects of the given type.
"""
if typ is None:
- raise MetadataError, "Can't replace default policy."
+ raise MetadataError("Can't replace default policy.")
- if self.policies.has_key( typ ):
- raise MetadataError, "Existing policy for content type:" + typ
+ if typ in self.policies:
+ raise MetadataError("Existing policy for content type:" + typ)
- self.policies[ typ ] = self._makePolicy()
+ self.policies[typ] = self._makePolicy()
security.declareProtected(ManagePortal, 'removePolicy')
- def removePolicy( self, typ ):
+ def removePolicy(self, typ):
""" Remove the policy from this element for objects of the given type.
o Do *not* remvoe the default, however.
"""
if typ is None:
- raise MetadataError, "Can't remove default policy."
- del self.policies[ typ ]
+ raise MetadataError("Can't remove default policy.")
+ del self.policies[typ]
-InitializeClass( ElementSpec )
+InitializeClass(ElementSpec)
-class MetadataSchema( SimpleItem ):
+class MetadataSchema(SimpleItem):
""" Describe a metadata schema.
"""
@@ -192,117 +190,100 @@
meta_type = 'Metadata Schema'
publisher = ''
- def __init__( self, id, element_specs=() ):
- self._setId( id )
+ def __init__(self, id, element_specs=()):
+ self._setId(id)
self.element_specs = PersistentMapping()
for name, is_multi_valued in element_specs:
- self.element_specs[ name ] = ElementSpec( is_multi_valued )
+ self.element_specs[name] = ElementSpec(is_multi_valued)
-
#
# ZMI methods
#
- manage_options = ( ( { 'label' : 'Elements'
- , 'action' : 'elementPoliciesForm'
- }
- ,
- )
- + SimpleItem.manage_options
- )
+ manage_options = (
+ ({'label': 'Elements', 'action': 'elementPoliciesForm'},) +
+ SimpleItem.manage_options)
security.declareProtected(ManagePortal, 'elementPoliciesForm')
- elementPoliciesForm = DTMLFile( 'metadataElementPolicies', _dtmldir )
+ elementPoliciesForm = DTMLFile('metadataElementPolicies', _dtmldir)
security.declareProtected(ManagePortal, 'addElementPolicy')
- def addElementPolicy( self
- , element
- , content_type
- , is_required
- , supply_default
- , default_value
- , enforce_vocabulary
- , allowed_vocabulary
- , REQUEST=None
- ):
+ def addElementPolicy(self,
+ element,
+ content_type,
+ is_required,
+ supply_default,
+ default_value,
+ enforce_vocabulary,
+ allowed_vocabulary,
+ REQUEST=None):
""" Add a type-specific policy for one of our elements.
"""
if content_type == '<default>':
content_type = None
- spec = self.getElementSpec( element )
- spec.addPolicy( content_type )
- policy = spec.getPolicy( content_type )
- policy.edit( is_required
- , supply_default
- , default_value
- , enforce_vocabulary
- , allowed_vocabulary
- )
+ spec = self.getElementSpec(element)
+ spec.addPolicy(content_type)
+ policy = spec.getPolicy(content_type)
+ policy.edit(is_required,
+ supply_default,
+ default_value,
+ enforce_vocabulary,
+ allowed_vocabulary)
if REQUEST is not None:
- REQUEST[ 'RESPONSE' ].redirect( self.absolute_url()
- + '/elementPoliciesForm'
- + '?element=' + element
- + '&manage_tabs_message=Policy+added.'
- )
+ REQUEST['RESPONSE'].redirect(self.absolute_url()
+ + '/elementPoliciesForm'
+ + '?element=' + element
+ + '&manage_tabs_message=Policy+added.')
security.declareProtected(ManagePortal, 'removeElementPolicy')
- def removeElementPolicy( self
- , element
- , content_type
- , REQUEST=None
- ):
+ def removeElementPolicy(self, element, content_type, REQUEST=None):
""" Remvoe a type-specific policy for one of our elements.
"""
if content_type == '<default>':
content_type = None
- spec = self.getElementSpec( element )
- spec.removePolicy( content_type )
+ spec = self.getElementSpec(element)
+ spec.removePolicy(content_type)
if REQUEST is not None:
- REQUEST[ 'RESPONSE' ].redirect( self.absolute_url()
- + '/elementPoliciesForm'
- + '?element=' + element
- + '&manage_tabs_message=Policy+removed.'
- )
+ REQUEST['RESPONSE'].redirect(self.absolute_url()
+ + '/elementPoliciesForm'
+ + '?element=' + element
+ + '&manage_tabs_message=Policy+removed.')
security.declareProtected(ManagePortal, 'updateElementPolicy')
- def updateElementPolicy( self
- , element
- , content_type
- , is_required
- , supply_default
- , default_value
- , enforce_vocabulary
- , allowed_vocabulary
- , REQUEST=None
- ):
- """ Update a policy for one of our elements
+ def updateElementPolicy(self,
+ element,
+ content_type,
+ is_required,
+ supply_default,
+ default_value,
+ enforce_vocabulary,
+ allowed_vocabulary,
+ REQUEST=None):
+ """ Update a policy for one of our elements
o 'content_type' will be '<default>' when we edit the default.
"""
if content_type == '<default>':
content_type = None
- spec = self.getElementSpec( element )
- policy = spec.getPolicy( content_type )
- policy.edit( is_required
- , supply_default
- , default_value
- , enforce_vocabulary
- , allowed_vocabulary
- )
+ spec = self.getElementSpec(element)
+ policy = spec.getPolicy(content_type)
+ policy.edit(is_required,
+ supply_default,
+ default_value,
+ enforce_vocabulary,
+ allowed_vocabulary)
if REQUEST is not None:
- REQUEST[ 'RESPONSE' ].redirect( self.absolute_url()
- + '/elementPoliciesForm'
- + '?element=' + element
- + '&manage_tabs_message=Policy+updated.'
- )
+ REQUEST['RESPONSE'].redirect(self.absolute_url()
+ + '/elementPoliciesForm'
+ + '?element=' + element
+ + '&manage_tabs_message=Policy+updated.')
-
#
# Element spec manipulation.
#
security.declareProtected(ManagePortal, 'listElementSpecs')
- def listElementSpecs( self ):
+ def listElementSpecs(self):
""" Return a list of ElementSpecs representing the elements we manage.
"""
res = []
@@ -311,61 +292,59 @@
return res
security.declareProtected(ManagePortal, 'getElementSpec')
- def getElementSpec( self, element ):
+ def getElementSpec(self, element):
""" Return an ElementSpec for the given 'element'.
"""
- return self.element_specs[ element ].__of__( self )
+ return self.element_specs[element].__of__(self)
security.declareProtected(ManagePortal, 'addElementSpec')
- def addElementSpec( self, element, is_multi_valued, REQUEST=None ):
+ def addElementSpec(self, element, is_multi_valued, REQUEST=None):
""" Add 'element' to our list of managed elements.
"""
# Don't replace.
- if self.element_specs.has_key( element ):
+ if element in self.element_specs:
return
- self.element_specs[ element ] = ElementSpec( is_multi_valued )
+ self.element_specs[element] = ElementSpec(is_multi_valued)
if REQUEST is not None:
- REQUEST[ 'RESPONSE' ].redirect( self.absolute_url()
- + '/propertiesForm'
- + '?manage_tabs_message=Element+' + element + '+added.'
- )
+ REQUEST['RESPONSE'].redirect(self.absolute_url()
+ + '/propertiesForm'
+ + '?manage_tabs_message=Element+' + element + '+added.')
security.declareProtected(ManagePortal, 'removeElementSpec')
- def removeElementSpec( self, element, REQUEST=None ):
+ def removeElementSpec(self, element, REQUEST=None):
""" Remove 'element' from our list of managed elements.
"""
- del self.element_specs[ element ]
+ del self.element_specs[element]
if REQUEST is not None:
- REQUEST[ 'RESPONSE' ].redirect( self.absolute_url()
- + '/propertiesForm'
- + '?manage_tabs_message=Element+' + element + '+removed.'
- )
+ REQUEST['RESPONSE'].redirect(self.absolute_url()
+ + '/propertiesForm'
+ + '?manage_tabs_message=Element+' + element + '+removed.')
security.declareProtected(ManagePortal, 'listPolicies')
- def listPolicies( self, typ=None ):
+ def listPolicies(self, typ=None):
""" Show all policies for a given content type
o If 'typ' is none, return the list of default policies.
"""
result = []
for element, spec in self.listElementSpecs():
- result.append( ( element, spec.getPolicy( typ ) ) )
+ result.append((element, spec.getPolicy(typ)))
return result
InitializeClass(MetadataSchema)
-_DCMI_ELEMENT_SPECS = ( ( 'Title', 0 )
- , ( 'Description', 0 )
- , ( 'Subject', 1 )
- , ( 'Format', 0 )
- , ( 'Language', 0 )
- , ( 'Rights', 0 )
- )
+_DCMI_ELEMENT_SPECS = (('Title', 0),
+ ('Description', 0),
+ ('Subject', 1),
+ ('Format', 0),
+ ('Language', 0),
+ ('Rights', 0))
+
class MetadataTool(UniqueObject, Folder):
implements(IMetadataTool)
@@ -376,11 +355,11 @@
#
# Default values.
#
- publisher = ''
+ publisher = ''
security = ClassSecurityInfo()
- def __init__( self, publisher=None ):
+ def __init__(self, publisher=None):
self.editProperties(publisher)
self.DCMI = MetadataSchema('DCMI', _DCMI_ELEMENT_SPECS)
@@ -388,206 +367,190 @@
#
# ZMI methods
#
- manage_options = ( ( { 'label' : 'Schema'
- , 'action' : 'propertiesForm'
- }
- , { 'label' : 'Overview'
- , 'action' : 'manage_overview'
- }
- )
- + Folder.manage_options
- )
+ manage_options = (
+ ({'label': 'Schema', 'action': 'propertiesForm'},
+ {'label': 'Overview', 'action': 'manage_overview'}) +
+ Folder.manage_options)
security.declareProtected(ManagePortal, 'manage_overview')
- manage_overview = DTMLFile( 'explainMetadataTool', _dtmldir )
+ manage_overview = DTMLFile('explainMetadataTool', _dtmldir)
security.declareProtected(ManagePortal, 'propertiesForm')
- propertiesForm = DTMLFile( 'metadataProperties', _dtmldir )
+ propertiesForm = DTMLFile('metadataProperties', _dtmldir)
security.declareProtected(ManagePortal, 'editProperties')
- def editProperties( self
- , publisher=None
- , REQUEST=None
- ):
- """ Form handler for "tool-wide" properties
+ def editProperties(self, publisher=None, REQUEST=None):
+ """ Form handler for "tool-wide" properties
"""
if publisher is not None:
self.publisher = publisher
if REQUEST is not None:
- REQUEST[ 'RESPONSE' ].redirect( self.absolute_url()
- + '/propertiesForm'
- + '?manage_tabs_message=Tool+updated.'
- )
+ REQUEST['RESPONSE'].redirect(self.absolute_url()
+ + '/propertiesForm'
+ + '?manage_tabs_message=Tool+updated.')
security.declareProtected(ManagePortal, 'manage_addSchema')
- def manage_addSchema( self, schema_id, elements, REQUEST ):
+ def manage_addSchema(self, schema_id, elements, REQUEST):
""" ZMI wrapper around addSchema
"""
massaged = []
for element in elements:
if isinstance(element, basestring):
element = element.split(',')
- if len( element ) < 2:
+ if len(element) < 2:
element.append(0)
- massaged.append( element )
- self.addSchema( schema_id, massaged )
+ massaged.append(element)
+ self.addSchema(schema_id, massaged)
- REQUEST['RESPONSE'].redirect( self.absolute_url()
- + '/propertiesForm'
- + '?manage_tabs_message=Schema+added.'
- )
+ REQUEST['RESPONSE'].redirect(self.absolute_url()
+ + '/propertiesForm'
+ + '?manage_tabs_message=Schema+added.')
security.declareProtected(ManagePortal, 'manage_removeSchemas')
- def manage_removeSchemas( self, schema_ids, REQUEST ):
+ def manage_removeSchemas(self, schema_ids, REQUEST):
""" ZMI wrapper around removeSchema
"""
if not schema_ids:
- raise ValueError, 'No schemas selected!'
+ raise ValueError('No schemas selected!')
for schema_id in schema_ids:
- self.removeSchema( schema_id )
+ self.removeSchema(schema_id)
- REQUEST['RESPONSE'].redirect( self.absolute_url()
- + '/propertiesForm'
- + '?manage_tabs_message=Schemas+removed.'
- )
+ REQUEST['RESPONSE'].redirect(self.absolute_url()
+ + '/propertiesForm'
+ + '?manage_tabs_message=Schemas+removed.')
- security.declarePrivate( 'getFullName' )
- def getFullName( self, userid ):
+ security.declarePrivate('getFullName')
+ def getFullName(self, userid):
""" See IMetadataTool.
"""
return userid # TODO: do lookup here
- security.declarePublic( 'getPublisher' )
- def getPublisher( self ):
+ security.declarePublic('getPublisher')
+ def getPublisher(self):
""" See IMetadataTool.
"""
return self.publisher
- security.declarePublic( 'listAllowedSubjects' )
- def listAllowedSubjects( self, content=None, content_type=None ):
+ security.declarePublic('listAllowedSubjects')
+ def listAllowedSubjects(self, content=None, content_type=None):
""" See IMetadataTool.
"""
- return self.listAllowedVocabulary( 'DCMI'
- , 'Subject'
- , content
- , content_type
- )
+ return self.listAllowedVocabulary('DCMI',
+ 'Subject',
+ content,
+ content_type)
- security.declarePublic( 'listAllowedFormats' )
- def listAllowedFormats( self, content=None, content_type=None ):
+ security.declarePublic('listAllowedFormats')
+ def listAllowedFormats(self, content=None, content_type=None):
""" See IMetadataTool.
"""
- return self.listAllowedVocabulary( 'DCMI'
- , 'Format'
- , content
- , content_type
- )
+ return self.listAllowedVocabulary('DCMI',
+ 'Format',
+ content,
+ content_type)
- security.declarePublic( 'listAllowedLanguages' )
- def listAllowedLanguages( self, content=None, content_type=None ):
+ security.declarePublic('listAllowedLanguages')
+ def listAllowedLanguages(self, content=None, content_type=None):
""" See IMetadataTool.
"""
- return self.listAllowedVocabulary( 'DCMI'
- , 'Language'
- , content
- , content_type
- )
+ return self.listAllowedVocabulary('DCMI',
+ 'Language',
+ content,
+ content_type)
- security.declarePublic( 'listAllowedRights' )
- def listAllowedRights( self, content=None, content_type=None ):
+ security.declarePublic('listAllowedRights')
+ def listAllowedRights(self, content=None, content_type=None):
""" See IMetadata Tool.
"""
- return self.listAllowedVocabulary( 'DCMI'
- , 'Rights'
- , content
- , content_type
- )
+ return self.listAllowedVocabulary('DCMI',
+ 'Rights',
+ content,
+ content_type)
- security.declarePublic( 'listAllowedVocabulary' )
- def listAllowedVocabulary( self
- , schema
- , element
- , content=None
- , content_type=None
- ):
+ security.declarePublic('listAllowedVocabulary')
+ def listAllowedVocabulary(self,
+ schema,
+ element,
+ content=None,
+ content_type=None):
""" See IMetadataTool.
"""
- schema_def = getattr( self, schema )
- spec = schema_def.getElementSpec( element )
+ schema_def = getattr(self, schema)
+ spec = schema_def.getElementSpec(element)
if content_type is None and content:
content_type = content.getPortalTypeName()
- return spec.getPolicy( content_type ).allowedVocabulary()
+ return spec.getPolicy(content_type).allowedVocabulary()
- security.declarePublic( 'listSchemas' )
- def listSchemas( self ):
+ security.declarePublic('listSchemas')
+ def listSchemas(self):
""" See IMetadataTool.
"""
- result = [ ( 'DCMI', self.DCMI ) ]
- result.extend( self.objectItems( [ MetadataSchema.meta_type ] ) )
+ result = [('DCMI', self.DCMI)]
+ result.extend(self.objectItems([MetadataSchema.meta_type]))
return result
security.declareProtected(ModifyPortalContent, 'addSchema')
- def addSchema( self, schema_id, elements=() ):
+ def addSchema(self, schema_id, elements=()):
""" See IMetadataTool.
"""
if schema_id == 'DCMI' or schema_id in self.objectIds():
- raise KeyError, 'Duplicate schema ID: %s' % schema_id
+ raise KeyError('Duplicate schema ID: %s' % schema_id)
- schema = MetadataSchema( schema_id, elements )
- self._setObject( schema_id, schema )
+ schema = MetadataSchema(schema_id, elements)
+ self._setObject(schema_id, schema)
- return self._getOb( schema_id )
+ return self._getOb(schema_id)
security.declareProtected(ModifyPortalContent, 'removeSchema')
- def removeSchema( self, schema_id ):
+ def removeSchema(self, schema_id):
""" See IMetadataTool.
"""
if schema_id == 'DCMI' or schema_id not in self.objectIds():
- raise KeyError, 'Invalid schema ID: %s' % schema_id
+ raise KeyError('Invalid schema ID: %s' % schema_id)
- self._delObject( schema_id )
+ self._delObject(schema_id)
security.declareProtected(ModifyPortalContent, 'setInitialMetadata')
- def setInitialMetadata( self, content ):
+ def setInitialMetadata(self, content):
""" See IMetadataTool.
"""
for _schema_id, schema in self.listSchemas():
for element, policy in schema.listPolicies(
content.getPortalTypeName()):
- if not getattr( content, element )():
+ if not getattr(content, element)():
if policy.supplyDefault():
- setter = getattr( content, 'set%s' % element )
- setter( policy.defaultValue() )
+ setter = getattr(content, 'set%s' % element)
+ setter(policy.defaultValue())
elif policy.isRequired():
- raise MetadataError, \
- 'Metadata element %s is required.' % element
+ raise MetadataError('Metadata element %s is required.'
+ % element)
# TODO: Call initial_values_hook, if present
security.declareProtected(View, 'validateMetadata')
- def validateMetadata( self, content ):
+ def validateMetadata(self, content):
""" See IMetadataTool.
"""
for _schema_id, schema in self.listSchemas():
for element, policy in schema.listPolicies(
content.getPortalTypeName()):
- value = getattr( content, element )()
+ value = getattr(content, element)()
if not value and policy.isRequired():
- raise MetadataError, \
- 'Metadata element %s is required.' % element
+ raise MetadataError('Metadata element %s is required.'
+ % element)
if value and policy.enforceVocabulary():
- values = policy.isMultiValued() and value or [ value ]
+ values = policy.isMultiValued() and value or [value]
for value in values:
if not value in policy.allowedVocabulary():
- raise MetadataError, \
- 'Value %s is not in allowed vocabulary for ' \
- 'metadata element %s.' % ( value, element )
+ raise MetadataError(
+ 'Value %s is not in allowed vocabulary for '
+ 'metadata element %s.' % (value, element))
InitializeClass(MetadataTool)
registerToolInterface('portal_metadata', IMetadataTool)
Modified: Products.CMFDefault/trunk/Products/CMFDefault/browser/membership/authentication.py
===================================================================
--- Products.CMFDefault/trunk/Products/CMFDefault/browser/membership/authentication.py 2012-04-24 10:35:58 UTC (rev 125265)
+++ Products.CMFDefault/trunk/Products/CMFDefault/browser/membership/authentication.py 2012-04-24 10:36:19 UTC (rev 125266)
@@ -77,7 +77,7 @@
req = self.request
if (not req['REQUEST_METHOD'] in ('HEAD', 'GET', 'PUT', 'POST')
- or req.environ.has_key('WEBDAV_SOURCE_PORT')):
+ or 'WEBDAV_SOURCE_PORT' in req.environ):
# re-raise the unhandled exception
raise self.context
@@ -211,6 +211,7 @@
return self._setRedirect('portal_actions', 'user/logged_in',
'came_from')
+
class LoggedIn(ViewBase):
"""Post login methods"""
@@ -278,7 +279,7 @@
else:
ac_name_id = '__ac_name'
ac_name = self.request.get(ac_name_id)
- if ac_name and not self.request.has_key('%s.name' % self.prefix):
+ if ac_name and not ('%s.name' % self.prefix) in self.request:
self.request.form['%s.name' % self.prefix] = ac_name
super(MailPasswordFormView,
self).setUpWidgets(ignore_request=ignore_request)
Modified: Products.CMFDefault/trunk/Products/CMFDefault/skins/zpt_control/personalize.py
===================================================================
--- Products.CMFDefault/trunk/Products/CMFDefault/skins/zpt_control/personalize.py 2012-04-24 10:35:58 UTC (rev 125265)
+++ Products.CMFDefault/trunk/Products/CMFDefault/skins/zpt_control/personalize.py 2012-04-24 10:36:19 UTC (rev 125266)
@@ -1,7 +1,7 @@
## Script (Python) "personalize"
##title=Personalization Handler.
##parameters=
-REQUEST=context.REQUEST
+REQUEST = context.REQUEST
member = context.portal_membership.getAuthenticatedMember()
failMessage = context.portal_registration.testPropertiesValidity(REQUEST,
@@ -13,7 +13,7 @@
member.setProperties(REQUEST)
-if REQUEST.has_key('portal_skin'):
+if 'portal_skin' in REQUEST:
context.portal_skins.updateSkinCookie()
qs = '/personalize_form?portal_status_message=Member+changed.'
Modified: Products.CMFDefault/trunk/Products/CMFDefault/skins/zpt_generic/getBatchNavigation.py
===================================================================
--- Products.CMFDefault/trunk/Products/CMFDefault/skins/zpt_generic/getBatchNavigation.py 2012-04-24 10:35:58 UTC (rev 125265)
+++ Products.CMFDefault/trunk/Products/CMFDefault/skins/zpt_generic/getBatchNavigation.py 2012-04-24 10:36:19 UTC (rev 125266)
@@ -1,7 +1,7 @@
##parameters=batch_obj, target, type_singular='item', type_plural='items', previous_text='Previous', next_text='Next', **kw
##
from ZTUtils import make_query
-if kw.has_key('portal_status_message'):
+if 'portal_status_message' in kw:
del kw['portal_status_message']
navigation = {}
@@ -15,11 +15,11 @@
if not v:
del kw[k]
- query = kw and ( '?%s' % make_query(kw) ) or ''
+ query = kw and ('?%s' % make_query(kw)) or ''
url = '%s%s' % (target, query)
- items.append( {'length': length > 1 and length or '',
- 'type': length == 1 and type_singular or type_plural,
- 'url': length and url or ''} )
+ items.append({'length': length > 1 and length or '',
+ 'type': length == 1 and type_singular or type_plural,
+ 'url': length and url or ''})
navigation['previous'] = items[0]
navigation['previous']['text'] = previous_text
navigation['next'] = items[1]
Modified: Products.CMFDefault/trunk/Products/CMFDefault/skins/zpt_generic/roster.pt
===================================================================
--- Products.CMFDefault/trunk/Products/CMFDefault/skins/zpt_generic/roster.pt 2012-04-24 10:35:58 UTC (rev 125265)
+++ Products.CMFDefault/trunk/Products/CMFDefault/skins/zpt_generic/roster.pt 2012-04-24 10:36:19 UTC (rev 125266)
@@ -2,7 +2,7 @@
<body>
<metal:slot metal:fill-slot="main">
-<div tal:condition="python:not(request.has_key('bs'))"
+<div tal:condition="python:not('bs' in request)"
tal:define="dummy python:request.set('bs', '25')"></div>
<div metal:define-macro="roster"
Modified: Products.CMFDefault/trunk/Products/CMFDefault/tests/test_SyndicationInfo.py
===================================================================
--- Products.CMFDefault/trunk/Products/CMFDefault/tests/test_SyndicationInfo.py 2012-04-24 10:35:58 UTC (rev 125265)
+++ Products.CMFDefault/trunk/Products/CMFDefault/tests/test_SyndicationInfo.py 2012-04-24 10:36:19 UTC (rev 125266)
@@ -70,7 +70,7 @@
settings = {'max_items': 10, 'frequency': 7, 'period': 'daily',
'base': datetime.today()}
annotations = getAdapter(adapter.context, IAnnotations)
- self.assertFalse(annotations.has_key(adapter.key))
+ self.assertFalse(adapter.key in annotations)
annotations[adapter.key] = settings
for k, v in settings.items():
self.assertEqual(getattr(adapter, k), v)
@@ -113,7 +113,7 @@
class DummySyndicationTool(object):
- enabled = 0
+ enabled = 0
period = 'daily'
frequency = 1
base = datetime(2010, 10, 3, 12, 0, 0)
Modified: Products.CMFDefault/trunk/Products/CMFDefault/utils.py
===================================================================
--- Products.CMFDefault/trunk/Products/CMFDefault/utils.py 2012-04-24 10:35:58 UTC (rev 125265)
+++ Products.CMFDefault/trunk/Products/CMFDefault/utils.py 2012-04-24 10:36:19 UTC (rev 125266)
@@ -41,7 +41,7 @@
from Products.CMFDefault.exceptions import IllegalHTML
from Products.CMFDefault.interfaces import IHTMLScrubber
-security = ModuleSecurityInfo( 'Products.CMFDefault.utils' )
+security = ModuleSecurityInfo('Products.CMFDefault.utils')
try:
get_distribution('Products.CMFCalendar')
@@ -58,34 +58,34 @@
PRODUCTS_CMFUID_INSTALLED = True
security.declarePrivate('_dtmldir')
-_dtmldir = os.path.join( package_home( globals() ), 'dtml' )
-_wwwdir = os.path.join( package_home( globals() ), 'www' )
+_dtmldir = os.path.join(package_home(globals()), 'dtml')
+_wwwdir = os.path.join(package_home(globals()), 'www')
security.declarePublic('formatRFC822Headers')
-def formatRFC822Headers( headers ):
+def formatRFC822Headers(headers):
""" Convert the key-value pairs in 'headers' to valid RFC822-style
headers, including adding leading whitespace to elements which
contain newlines in order to preserve continuation-line semantics.
"""
munged = []
- linesplit = re.compile( r'[\n\r]+?' )
+ linesplit = re.compile(r'[\n\r]+?')
for key, value in headers:
- vallines = linesplit.split( value )
+ vallines = linesplit.split(value)
while vallines:
if vallines[-1].rstrip() == '':
vallines = vallines[:-1]
else:
break
- munged.append( '%s: %s' % ( key, '\r\n '.join( vallines ) ) )
+ munged.append('%s: %s' % (key, '\r\n '.join(vallines)))
- return '\r\n'.join( munged )
+ return '\r\n'.join(munged)
security.declarePublic('parseHeadersBody')
-def parseHeadersBody( body, headers=None, rc=re.compile( r'\n|\r\n' ) ):
+def parseHeadersBody(body, headers=None, rc=re.compile(r'\n|\r\n')):
""" Parse any leading 'RFC-822'-ish headers from an uploaded
document, returning a dictionary containing the headers
@@ -136,86 +136,86 @@
""" Split 's' on semicolons.
"""
- return map(lambda x: x.strip(), s.split( ';' ) )
+ return map(lambda x: x.strip(), s.split(';'))
security.declarePublic('comma_split')
def comma_split(s):
""" Split 's' on commas.
"""
- return map(lambda x: x.strip(), s.split( ',') )
+ return map(lambda x: x.strip(), s.split(','))
security.declarePublic('seq_strip')
-def seq_strip(seq, stripper=lambda x: x.strip() ):
+def seq_strip(seq, stripper=lambda x: x.strip()):
""" Strip a sequence of strings.
"""
if isinstance(seq, list):
- return map( stripper, seq )
+ return map(stripper, seq)
if isinstance(seq, tuple):
- return tuple( map( stripper, seq ) )
+ return tuple(map(stripper, seq))
- raise ValueError, "%s of unsupported sequencetype %s" % ( seq, type( seq ) )
+ raise ValueError("%s of unsupported sequencetype %s" % (seq, type(seq)))
security.declarePublic('tuplize')
-def tuplize( valueName, value, splitter=lambda x: x.split() ):
+def tuplize(valueName, value, splitter=lambda x: x.split()):
if isinstance(value, tuple):
- return seq_strip( value )
+ return seq_strip(value)
if isinstance(value, list):
- return seq_strip( tuple( value ) )
+ return seq_strip(tuple(value))
if isinstance(value, basestring):
- return seq_strip( tuple( splitter( value ) ) )
+ return seq_strip(tuple(splitter(value)))
- raise ValueError, "%s of unsupported type" % valueName
+ raise ValueError("%s of unsupported type" % valueName)
-class SimpleHTMLParser( SGMLParser ):
+class SimpleHTMLParser(SGMLParser):
#from htmlentitydefs import entitydefs
- def __init__( self, verbose=0 ):
+ def __init__(self, verbose=0):
- SGMLParser.__init__( self, verbose )
+ SGMLParser.__init__(self, verbose)
self.savedata = None
self.title = ''
self.metatags = {}
self.body = ''
- def handle_data( self, data ):
+ def handle_data(self, data):
if self.savedata is not None:
self.savedata = self.savedata + data
- def handle_charref( self, ref ):
+ def handle_charref(self, ref):
- self.handle_data( "&#%s;" % ref )
+ self.handle_data("&#%s;" % ref)
- def handle_entityref( self, ref ):
+ def handle_entityref(self, ref):
- self.handle_data( "&%s;" % ref )
+ self.handle_data("&%s;" % ref)
- def save_bgn( self ):
+ def save_bgn(self):
self.savedata = ''
- def save_end( self ):
+ def save_end(self):
data = self.savedata
self.savedata = None
return data
- def start_title( self, attrs ):
+ def start_title(self, attrs):
self.save_bgn()
- def end_title( self ):
+ def end_title(self):
self.title = self.save_end()
- def do_meta( self, attrs ):
+ def do_meta(self, attrs):
name = ''
content = ''
@@ -231,13 +231,13 @@
content = value
if name:
- self.metatags[ name ] = content
+ self.metatags[name] = content
- def unknown_startag( self, tag, attrs ):
+ def unknown_startag(self, tag, attrs):
self.setliteral()
- def unknown_endtag( self, tag ):
+ def unknown_endtag(self, tag):
self.setliteral()
@@ -246,88 +246,84 @@
#
# These are the HTML tags that we will leave intact
-VALID_TAGS = { 'a' : 1
- , 'b' : 1
- , 'base' : 0
- , 'big' : 1
- , 'blockquote' : 1
- , 'body' : 1
- , 'br' : 0
- , 'caption' : 1
- , 'cite' : 1
- , 'code' : 1
- , 'dd' : 1
- , 'div' : 1
- , 'dl' : 1
- , 'dt' : 1
- , 'em' : 1
- , 'h1' : 1
- , 'h2' : 1
- , 'h3' : 1
- , 'h4' : 1
- , 'h5' : 1
- , 'h6' : 1
- , 'head' : 1
- , 'hr' : 0
- , 'html' : 1
- , 'i' : 1
- , 'img' : 0
- , 'kbd' : 1
- , 'li' : 1
- # , 'link' : 1 type="script" hoses us
- , 'meta' : 0
- , 'ol' : 1
- , 'p' : 1
- , 'pre' : 1
- , 'small' : 1
- , 'span' : 1
- , 'strong' : 1
- , 'sub' : 1
- , 'sup' : 1
- , 'table' : 1
- , 'tbody' : 1
- , 'td' : 1
- , 'th' : 1
- , 'title' : 1
- , 'tr' : 1
- , 'tt' : 1
- , 'u' : 1
- , 'ul' : 1
- }
+VALID_TAGS = {'a': 1,
+ 'b': 1,
+ 'base': 0,
+ 'big': 1,
+ 'blockquote': 1,
+ 'body': 1,
+ 'br': 0,
+ 'caption': 1,
+ 'cite': 1,
+ 'code': 1,
+ 'dd': 1,
+ 'div': 1,
+ 'dl': 1,
+ 'dt': 1,
+ 'em': 1,
+ 'h1': 1,
+ 'h2': 1,
+ 'h3': 1,
+ 'h4': 1,
+ 'h5': 1,
+ 'h6': 1,
+ 'head': 1,
+ 'hr': 0,
+ 'html': 1,
+ 'i': 1,
+ 'img': 0,
+ 'kbd': 1,
+ 'li': 1,
+ # 'link': 1, type="script" hoses us
+ 'meta': 0,
+ 'ol': 1,
+ 'p': 1,
+ 'pre': 1,
+ 'small': 1,
+ 'span': 1,
+ 'strong': 1,
+ 'sub': 1,
+ 'sup': 1,
+ 'table': 1,
+ 'tbody': 1,
+ 'td': 1,
+ 'th': 1,
+ 'title': 1,
+ 'tr': 1,
+ 'tt': 1,
+ 'u': 1,
+ 'ul': 1}
-NASTY_TAGS = { 'script' : 1
- , 'object' : 1
- , 'embed' : 1
- , 'applet' : 1
- }
+NASTY_TAGS = {'script': 1,
+ 'object': 1,
+ 'embed': 1,
+ 'applet': 1}
-class StrippingParser( SGMLParser ):
+class StrippingParser(SGMLParser):
""" Pass only allowed tags; raise exception for known-bad.
"""
from htmlentitydefs import entitydefs # replace entitydefs from sgmllib
- def __init__( self, valid_tags=None, nasty_tags=None ):
+ def __init__(self, valid_tags=None, nasty_tags=None):
- SGMLParser.__init__( self )
+ SGMLParser.__init__(self)
self.result = ""
self.valid_tags = valid_tags or VALID_TAGS
self.nasty_tags = nasty_tags or NASTY_TAGS
- def handle_data( self, data ):
+ def handle_data(self, data):
if data:
self.result = self.result + data
- def handle_charref( self, name ):
+ def handle_charref(self, name):
+ self.result = "%s&#%s;" % (self.result, name)
- self.result = "%s&#%s;" % ( self.result, name )
-
def handle_entityref(self, name):
-
- if self.entitydefs.has_key(name):
+ if name in self.entitydefs:
x = ';'
else:
# this breaks unstandard entities that end with ';'
@@ -338,7 +334,7 @@
def unknown_starttag(self, tag, attrs):
""" Delete all tags except for legal ones.
"""
- if self.valid_tags.has_key(tag):
+ if tag in self.valid_tags:
self.result = self.result + '<' + tag
@@ -379,7 +375,7 @@
security.declarePublic('scrubHTML')
-def scrubHTML( html ):
+def scrubHTML(html):
""" Strip illegal HTML tags from string text.
@@ -391,17 +387,17 @@
return scrubber.scrub(html)
parser = StrippingParser()
- parser.feed( html )
+ parser.feed(html)
parser.close()
return parser.result
security.declarePublic('isHTMLSafe')
-def isHTMLSafe( html ):
+def isHTMLSafe(html):
""" Would current HTML be permitted to be saved?
"""
try:
- scrubHTML( html )
+ scrubHTML(html)
except IllegalHTML:
return 0
else:
@@ -460,7 +456,7 @@
elif isinstance(value, list):
return [ toUnicode(val, charset) for val in value ]
elif isinstance(value, tuple):
- return tuple( [ toUnicode(val, charset) for val in value ] )
+ return tuple([ toUnicode(val, charset) for val in value ])
elif isinstance(value, dict):
for key, val in value.items():
value[key] = toUnicode(val, charset)
@@ -554,13 +550,13 @@
def thousands_commas(value):
"""Format an integer with commas as thousand separator"""
i = int(value)
- if sys.version_info[0] > 2 \
+ if sys.version_info[0] > 2 \
or (sys.version_info[0] == 2 and sys.version_info[1] > 6):
warn("On Python 2.7 and higher Use {:,}.formatting",
DeprecationWarning,
stacklevel=2)
return "{:,}".format(value)
l = list(str(i))
- for idx in range(len(l) -3, 0, -3):
+ for idx in range(len(l) - 3, 0, -3):
l.insert(idx, ",")
return "".join(l)
More information about the checkins
mailing list