add python3 suppport based on 2to3 script

This commit is contained in:
Stefan Klug 2015-10-27 21:10:24 +01:00
parent caef0e85d0
commit 4f91a30fec
68 changed files with 597 additions and 576 deletions

View file

@ -101,7 +101,7 @@ class BufferAction:
try:
res = self._evalExpr(expr, context)
error = False
except Exception, e:
except Exception as e:
res = None
errorMessage = EVAL_ERROR % (expr, self.getExceptionLine(e))
self.manageError(result, context, errorMessage)
@ -134,7 +134,7 @@ class BufferAction:
error = False
try:
feRes = eval(self.fromExpr, context)
except Exception, e:
except Exception as e:
msg = FROM_EVAL_ERROR% (self.fromExpr, self.getExceptionLine(e))
self.manageError(result, context, msg)
error = True
@ -240,7 +240,7 @@ class ForAction(BufferAction):
return
# Remember variable hidden by iter if any
hasHiddenVariable = False
if context.has_key(self.iter):
if self.iter in context:
hiddenVariable = context[self.iter]
hasHiddenVariable = True
# In the case of cells, initialize some values

View file

@ -80,15 +80,15 @@ NULL_ACTION_ERROR = 'There was a problem with this action. Possible causes: ' \
class BufferIterator:
def __init__(self, buffer):
self.buffer = buffer
self.remainingSubBufferIndexes = self.buffer.subBuffers.keys()
self.remainingElemIndexes = self.buffer.elements.keys()
self.remainingSubBufferIndexes = list(self.buffer.subBuffers.keys())
self.remainingElemIndexes = list(self.buffer.elements.keys())
self.remainingSubBufferIndexes.sort()
self.remainingElemIndexes.sort()
def hasNext(self):
return self.remainingSubBufferIndexes or self.remainingElemIndexes
def next(self):
def __next__(self):
nextSubBufferIndex = None
if self.remainingSubBufferIndexes:
nextSubBufferIndex = self.remainingSubBufferIndexes[0]
@ -131,7 +131,7 @@ class Buffer:
return subBuffer
def removeLastSubBuffer(self):
subBufferIndexes = self.subBuffers.keys()
subBufferIndexes = list(self.subBuffers.keys())
subBufferIndexes.sort()
lastIndex = subBufferIndexes.pop()
del self.subBuffers[lastIndex]
@ -176,7 +176,7 @@ class Buffer:
self.write('<%s' % elem)
# Some table elements must be patched (pod only)
if self.pod: self.patchTableElement(elem, attrs)
for name, value in attrs.items():
for name, value in list(attrs.items()):
if ignoreAttrs and (name in ignoreAttrs): continue
if renamedAttrs and (name in renamedAttrs): name=renamedAttrs[name]
# If the value begins with ':', it is a Python expression. Else,
@ -244,7 +244,7 @@ class FileBuffer(Buffer):
res, escape = expr.evaluate(self.env.context)
if escape: self.dumpContent(res)
else: self.write(res)
except Exception, e:
except Exception as e:
if not self.env.raiseOnError:
PodError.dump(self, EVAL_EXPR_ERROR % (expression, e),
dumpTb=False)
@ -271,7 +271,7 @@ class MemoryBuffer(Buffer):
def __init__(self, env, parent):
Buffer.__init__(self, env, parent)
self.content = u''
self.content = ''
self.elements = {}
self.action = None
@ -297,7 +297,7 @@ class MemoryBuffer(Buffer):
def getIndex(self, podElemName):
res = -1
for index, podElem in self.elements.iteritems():
for index, podElem in self.elements.items():
if podElem.__class__.__name__.lower() == podElemName:
if index > res:
res = index
@ -305,7 +305,7 @@ class MemoryBuffer(Buffer):
def getMainElement(self):
res = None
if self.elements.has_key(0):
if 0 in self.elements:
res = self.elements[0]
return res
@ -317,7 +317,7 @@ class MemoryBuffer(Buffer):
if elem != mainElem: return
# elem is the same as the main elem. But is it really the main elem, or
# the same elem, found deeper in the buffer?
for index, iElem in self.elements.iteritems():
for index, iElem in self.elements.items():
foundElem = None
if hasattr(iElem, 'OD'):
if iElem.OD:
@ -331,7 +331,7 @@ class MemoryBuffer(Buffer):
def unreferenceElement(self, elem):
# Find last occurrence of this element
elemIndex = -1
for index, iElem in self.elements.iteritems():
for index, iElem in self.elements.items():
foundElem = None
if hasattr(iElem, 'OD'):
# A POD element
@ -347,7 +347,7 @@ class MemoryBuffer(Buffer):
def pushSubBuffer(self, subBuffer):
'''Sets p_subBuffer at the very end of the buffer.'''
subIndex = None
for index, aSubBuffer in self.subBuffers.iteritems():
for index, aSubBuffer in self.subBuffers.items():
if aSubBuffer == subBuffer:
subIndex = index
break
@ -356,7 +356,7 @@ class MemoryBuffer(Buffer):
# in the parent (if it is a temp buffer generated from a cut)
del self.subBuffers[subIndex]
self.subBuffers[self.getLength()] = subBuffer
self.content += u' '
self.content += ' '
def transferAllContent(self):
'''Transfer all content to parent.'''
@ -370,10 +370,10 @@ class MemoryBuffer(Buffer):
oldParentLength = self.parent.getLength()
self.parent.write(self.content)
# Transfer elements
for index, podElem in self.elements.iteritems():
for index, podElem in self.elements.items():
self.parent.elements[oldParentLength + index] = podElem
# Transfer sub-buffers
for index, buf in self.subBuffers.iteritems():
for index, buf in self.subBuffers.items():
self.parent.subBuffers[oldParentLength + index] = buf
# Empty the buffer
MemoryBuffer.__init__(self, self.env, self.parent)
@ -391,7 +391,7 @@ class MemoryBuffer(Buffer):
elem.colIndex = elem.tableInfo.curColIndex
if elem == 'x':
# See comment on similar statement in the method below.
self.content += u' '
self.content += ' '
def addExpression(self, expression, tiedHook=None):
# Create the POD expression
@ -400,20 +400,20 @@ class MemoryBuffer(Buffer):
self.elements[self.getLength()] = expr
# To be sure that an expr and an elem can't be found at the same index
# in the buffer.
self.content += u' '
self.content += ' '
def addAttributes(self):
'''pod-only: adds an Attributes instance into this buffer.'''
attrs = Attributes(self.env)
self.elements[self.getLength()] = attrs
self.content += u' '
self.content += ' '
return attrs
def addAttribute(self, name, expr):
'''px-only: adds an Attribute instance into this buffer.'''
attr = Attribute(name, expr)
self.elements[self.getLength()] = attr
self.content += u' '
self.content += ' '
return attr
def _getVariables(self, expr):
@ -453,7 +453,7 @@ class MemoryBuffer(Buffer):
raise ParsingError(
ELEMENT_NOT_FOUND % (podElem, str([
e.__class__.__name__.lower() \
for e in self.elements.values()])))
for e in list(self.elements.values())])))
podElem = self.elements[indexPodElem]
# Check the 'from' clause
fromClause = None
@ -471,7 +471,7 @@ class MemoryBuffer(Buffer):
self.env.ifActions.append(self.action)
if self.action.name:
# We must register this action as a named action
if self.env.namedIfActions.has_key(self.action.name):
if self.action.name in self.env.namedIfActions:
raise ParsingError(DUPLICATE_NAMED_IF)
self.env.namedIfActions[self.action.name] = self.action
elif actionType == 'else':
@ -480,7 +480,7 @@ class MemoryBuffer(Buffer):
# Does the "else" action reference a named "if" action?
ifReference = subExpr.strip()
if ifReference:
if not self.env.namedIfActions.has_key(ifReference):
if ifReference not in self.env.namedIfActions:
raise ParsingError(ELSE_WITHOUT_NAMED_IF % ifReference)
linkedIfAction = self.env.namedIfActions[ifReference]
# This "else" action "consumes" the "if" action: this way,
@ -510,7 +510,7 @@ class MemoryBuffer(Buffer):
self.action = NullAction(statementName, self, None, podElem,
None, source, fromClause)
res = indexPodElem
except ParsingError, ppe:
except ParsingError as ppe:
PodError.dump(self, ppe, removeFirstLine=True)
return res
@ -552,7 +552,7 @@ class MemoryBuffer(Buffer):
elementsToDelete = []
mustShift = False
while iter.hasNext():
itemIndex, item = iter.next()
itemIndex, item = next(iter)
if keepFirstPart:
if itemIndex >= index:
newIndex = itemIndex-index
@ -580,11 +580,11 @@ class MemoryBuffer(Buffer):
del self.subBuffers[subIndex]
if mustShift:
elements = {}
for elemIndex, elem in self.elements.iteritems():
for elemIndex, elem in self.elements.items():
elements[elemIndex-index] = elem
self.elements = elements
subBuffers = {}
for subIndex, buf in self.subBuffers.iteritems():
for subIndex, buf in self.subBuffers.items():
subBuffers[subIndex-index] = buf
self.subBuffers = subBuffers
# Manage content
@ -598,7 +598,7 @@ class MemoryBuffer(Buffer):
def getElementIndexes(self, expressions=True):
res = []
for index, elem in self.elements.iteritems():
for index, elem in self.elements.items():
condition = isinstance(elem, Expression) or \
isinstance(elem, Attributes)
if not expressions:
@ -696,7 +696,7 @@ class MemoryBuffer(Buffer):
iter = BufferIterator(self)
currentIndex = self.getStartIndex(removeMainElems)
while iter.hasNext():
index, evalEntry = iter.next()
index, evalEntry = next(iter)
result.write(self.content[currentIndex:index])
currentIndex = index + 1
if isinstance(evalEntry, Expression):
@ -708,7 +708,7 @@ class MemoryBuffer(Buffer):
# This exception has already been treated (see the
# "except" block below). Simply re-raise it when needed.
if self.env.raiseOnError: raise e
except Exception, e:
except Exception as e:
if not self.env.raiseOnError:
PodError.dump(result, EVAL_EXPR_ERROR % (
evalEntry.expr, e))
@ -729,5 +729,5 @@ class MemoryBuffer(Buffer):
def clean(self):
'''Cleans the buffer content.'''
self.content = u''
self.content = ''
# ------------------------------------------------------------------------------

View file

@ -109,7 +109,7 @@ class Converter:
res = res[self.inputType]
else:
raise ConverterError(BAD_RESULT_TYPE % (self.resultType,
FILE_TYPES.keys()))
list(FILE_TYPES.keys())))
return res
def getResultUrl(self):
@ -275,7 +275,7 @@ class ConverterScript:
' %s.\n' \
' "python" should be a UNO-enabled Python interpreter (ie the ' \
' one which is included in the LibreOffice distribution).' % \
str(FILE_TYPES.keys())
str(list(FILE_TYPES.keys()))
def run(self):
optParser = OptionParser(usage=ConverterScript.usage)
optParser.add_option("-p", "--port", dest="port",

View file

@ -17,7 +17,7 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,USA.
# ------------------------------------------------------------------------------
import os, os.path, time, shutil, struct, random, urlparse
import os, os.path, time, shutil, struct, random, urllib.parse
from appy.pod import PodError
from appy.pod.odf_parser import OdfEnvironment
from appy.shared import mimeTypesExts
@ -53,7 +53,7 @@ class DocImporter:
if at and not at.startswith('http') and not os.path.isfile(at):
raise PodError(FILE_NOT_FOUND % at)
self.format = format
self.res = u''
self.res = ''
self.renderer = renderer
self.ns = renderer.currentParser.env.namespaces
# Unpack some useful namespaces
@ -285,7 +285,7 @@ class ImageImporter(DocImporter):
def moveFile(self, at, importPath):
'''Copies file at p_at into the ODT file at p_importPath.'''
# Has this image already been imported ?
for imagePath, imageAt in self.fileNames.iteritems():
for imagePath, imageAt in self.fileNames.items():
if imageAt == at:
# Yes!
i = importPath.rfind(self.pictFolder) + 1
@ -327,7 +327,7 @@ class ImageImporter(DocImporter):
# The imageResolver is a Zope application. From it, we will
# retrieve the object on which the image is stored and get
# the file to download.
urlParts = urlparse.urlsplit(at)
urlParts = urllib.parse.urlsplit(at)
path = urlParts[2][1:].split('/')[:-1]
try:
obj = imageResolver.unrestrictedTraverse(path)

View file

@ -148,7 +148,7 @@ class Expression(PodElement):
# pod/px result.
resultType = res.__class__.__name__
if resultType == 'NoneType':
res = u''
res = ''
elif resultType == 'str':
res = res.decode('utf-8')
elif resultType == 'unicode':
@ -160,7 +160,7 @@ class Expression(PodElement):
# Force escapeXml to False.
escapeXml = False
else:
res = unicode(res)
res = str(res)
return res, escapeXml
class Attributes(PodElement):
@ -199,7 +199,7 @@ class Attributes(PodElement):
try:
self.tiedExpression.evaluate(context)
self.tiedExpression.evaluated = True
except Exception, e:
except Exception as e:
# Don't set "evaluated" to True. This way, when the buffer will
# evaluate the expression directly, we will really evaluate it, so
# the error will be dumped into the pod result.
@ -208,7 +208,7 @@ class Attributes(PodElement):
self.computeAttributes(self.tiedExpression)
# Now, self.attrs has been populated. Transform it into a string.
res = ''
for name, value in self.attrs.iteritems():
for name, value in self.attrs.items():
res += ' %s=%s' % (name, quoteattr(value))
return res

View file

@ -50,7 +50,7 @@ class OdInsert:
def resolve(self, namespaces):
'''Replaces all unresolved namespaces in p_odtChunk, thanks to the dict
of p_namespaces.'''
for nsName, nsUri in self.nsUris.iteritems():
for nsName, nsUri in self.nsUris.items():
self.odtChunk = re.sub('@%s@' % nsName, namespaces[nsUri],
self.odtChunk)
return self.odtChunk
@ -126,14 +126,14 @@ class PodEnvironment(OdfEnvironment):
res = {}
for insert in self.inserts:
elemName = insert.elem.getFullName(self.namespaces)
if not res.has_key(elemName):
if elemName not in res:
res[elemName] = insert
return res
def manageInserts(self):
'''We just dumped the start of an elem. Here we will insert any odt
chunk if needed.'''
if self.inserts.has_key(self.currentElem.elem):
if self.currentElem.elem in self.inserts:
insert = self.inserts[self.currentElem.elem]
self.currentBuffer.write(insert.resolve(self.namespaces))
# The insert is destroyed after single use
@ -160,12 +160,12 @@ class PodEnvironment(OdfEnvironment):
elif elem == Cell.OD.elem:
colspan = 1
attrSpan = self.tags['number-columns-spanned']
if self.currentElem.attrs.has_key(attrSpan):
if attrSpan in self.currentElem.attrs:
colspan = int(self.currentElem.attrs[attrSpan])
self.getTable().curColIndex += colspan
elif elem == self.tags['table-column']:
attrs = self.currentElem.attrs
if attrs.has_key(self.tags['number-columns-repeated']):
if self.tags['number-columns-repeated'] in attrs:
self.getTable().nbOfColumns += int(
attrs[self.tags['number-columns-repeated']])
else:
@ -254,8 +254,8 @@ class PodParser(OdfParser):
e.state = e.READING_EXPRESSION
e.exprHasStyle = False
elif (elem == e.tags['table-cell']) and \
attrs.has_key(e.tags['formula']) and \
attrs.has_key(e.tags['value-type']) and \
e.tags['formula'] in attrs and \
e.tags['value-type'] in attrs and \
(attrs[e.tags['value-type']] == 'string') and \
attrs[e.tags['formula']].startswith('of:="'):
# In an ODS template, any cell containing a formula of type "string"

View file

@ -18,7 +18,11 @@
# ------------------------------------------------------------------------------
import zipfile, shutil, xml.sax, os, os.path, re, mimetypes, time
from UserDict import UserDict
#python3 compat
try:
from UserDict import UserDict
except ImportError:
from collections import UserDict
import appy.pod
from appy.pod import PodError
from appy.shared import mimeTypes, mimeTypesExts
@ -80,7 +84,7 @@ CONTENT_POD_FONTS = '<@style@:font-face @style@:name="PodStarSymbol" ' \
'@svg@:font-family="StarSymbol"/>'
# Default text styles added by pod in styles.xml
f = file('%s/styles.in.styles.xml' % os.path.dirname(appy.pod.__file__))
f = open('%s/styles.in.styles.xml' % os.path.dirname(appy.pod.__file__))
STYLES_POD_STYLES = f.read()
f.close()
@ -263,7 +267,7 @@ class Renderer:
imageFormats = ('png', 'jpeg', 'jpg', 'gif', 'svg')
ooFormats = ('odt',)
convertibleFormats = FILE_TYPES.keys()
convertibleFormats = list(FILE_TYPES.keys())
def importDocument(self, content=None, at=None, format=None,
anchor='as-char', wrapInPara=True, size=None,
sizeUnit='cm', style=None,
@ -309,7 +313,7 @@ class Renderer:
format = os.path.splitext(at)[1][1:]
else:
# If format is a mimeType, convert it to an extension
if mimeTypesExts.has_key(format):
if format in mimeTypesExts:
format = mimeTypesExts[format]
isImage = False
isOdt = False
@ -370,9 +374,9 @@ class Renderer:
f = open(self.result, 'w')
f.write('Hello')
f.close()
except OSError, oe:
except OSError as oe:
raise PodError(CANT_WRITE_RESULT % (self.result, oe))
except IOError, ie:
except IOError as ie:
raise PodError(CANT_WRITE_RESULT % (self.result, ie))
self.result = os.path.abspath(self.result)
os.remove(self.result)
@ -381,7 +385,7 @@ class Renderer:
self.tempFolder = '%s.%f' % (absResult, time.time())
try:
os.mkdir(self.tempFolder)
except OSError, oe:
except OSError as oe:
raise PodError(CANT_WRITE_TEMP_FOLDER % (self.result, oe))
def patchManifest(self):
@ -390,7 +394,7 @@ class Renderer:
if self.fileNames:
j = os.path.join
toInsert = ''
for fileName in self.fileNames.iterkeys():
for fileName in self.fileNames.keys():
if fileName.endswith('.svg'):
fileName = os.path.splitext(fileName)[0] + '.png'
mimeType = mimetypes.guess_type(fileName)[0]
@ -442,7 +446,7 @@ class Renderer:
if 'span[font-style=italic]' not in stylesMapping:
stylesMapping['span[font-style=italic]'] = 'podItalic'
self.stylesManager.stylesMapping = stylesMapping
except PodError, po:
except PodError as po:
self.contentParser.env.currentBuffer.content.close()
self.stylesParser.env.currentBuffer.content.close()
if os.path.exists(self.tempFolder):
@ -454,14 +458,14 @@ class Renderer:
loOutput = ''
try:
if (not isinstance(self.ooPort, int)) and \
(not isinstance(self.ooPort, long)):
(not isinstance(self.ooPort, int)):
raise PodError(BAD_OO_PORT % str(self.ooPort))
try:
from appy.pod.converter import Converter, ConverterError
try:
Converter(resultName, resultType, self.ooPort,
self.stylesTemplate).run()
except ConverterError, ce:
except ConverterError as ce:
raise PodError(CONVERT_ERROR % str(ce))
except ImportError:
# I do not have UNO. So try to launch a UNO-enabled Python
@ -485,13 +489,13 @@ class Renderer:
self.ooPort)
if self.stylesTemplate: cmd += ' -t%s' % self.stylesTemplate
loOutput = executeCommand(cmd)
except PodError, pe:
except PodError as pe:
# When trying to call LO in server mode for producing ODT or ODS
# (=forceOoCall=True), if an error occurs we have nevertheless
# an ODT or ODS to return to the user. So we produce a warning
# instead of raising an error.
if (resultType in self.templateTypes) and self.forceOoCall:
print(WARNING_INCOMPLETE_OD % str(pe))
print((WARNING_INCOMPLETE_OD % str(pe)))
else:
raise pe
return loOutput
@ -501,7 +505,7 @@ class Renderer:
(ods or odt). If self.template is a string, it is a file name and we
simply get its extension. Else, it is a binary file in a StringIO
instance, and we seek the mime type from the first bytes.'''
if isinstance(self.template, basestring):
if isinstance(self.template, str):
res = os.path.splitext(self.template)[1][1:]
else:
# A StringIO instance
@ -534,8 +538,8 @@ class Renderer:
if self.finalizeFunction:
try:
self.finalizeFunction(self.unzipFolder)
except Exception, e:
print(WARNING_FINALIZE_ERROR % str(e))
except Exception as e:
print((WARNING_FINALIZE_ERROR % str(e)))
# Re-zip the result, first as an OpenDocument file of the same type as
# the POD template (odt, ods...)
resultExt = self.getTemplateType()

View file

@ -18,7 +18,12 @@
# ------------------------------------------------------------------------------
import re, os.path
from UserDict import UserDict
#python3 compat
try:
from UserDict import UserDict
except ImportError:
from collections import UserDict
import appy.pod
from appy.pod import *
from appy.pod.odf_parser import OdfEnvironment, OdfParser
@ -93,7 +98,7 @@ class Styles(UserDict):
'''Tries to find a style which has level p_level. Returns None if no
such style exists.'''
res = None
for style in self.itervalues():
for style in self.values():
if (style.family == 'paragraph') and (style.outlineLevel == level):
res = style
break
@ -102,7 +107,7 @@ class Styles(UserDict):
'''Gets the style that has this p_displayName. Returns None if not
found.'''
res = None
for style in self.itervalues():
for style in self.values():
if style.displayName == displayName:
res = style
break
@ -111,9 +116,9 @@ class Styles(UserDict):
'''Returns a list of all the styles of the given p_stylesType.'''
res = []
if stylesType == 'all':
res = self.values()
res = list(self.values())
else:
for style in self.itervalues():
for style in self.values():
if (style.family == stylesType) and style.displayName:
res.append(style)
return res
@ -145,22 +150,22 @@ class StylesParser(OdfParser):
displayNameAttr = '%s:display-name' % e.ns(e.NS_STYLE)
# Create the style
style = Style(name=attrs[nameAttr], family=attrs[familyAttr])
if attrs.has_key(classAttr):
if classAttr in attrs:
style.styleClass = attrs[classAttr]
if attrs.has_key(displayNameAttr):
if displayNameAttr in attrs:
style.displayName = attrs[displayNameAttr]
# Record this style in the environment
e.styles[style.name] = style
e.currentStyle = style
levelKey = '%s:default-outline-level' % e.ns(e.NS_STYLE)
if attrs.has_key(levelKey) and attrs[levelKey].strip():
if levelKey in attrs and attrs[levelKey].strip():
style.outlineLevel = int(attrs[levelKey])
else:
if e.state == PARSING_STYLE:
# I am parsing tags within the style.
if elem == ('%s:text-properties' % e.ns(e.NS_STYLE)):
fontSizeKey = '%s:font-size' % e.ns(e.NS_FO)
if attrs.has_key(fontSizeKey):
if fontSizeKey in attrs:
e.currentStyle.setFontSize(attrs[fontSizeKey])
def endElement(self, elem):
e = OdfParser.endElement(self, elem)
@ -250,14 +255,14 @@ class StylesManager:
if not isinstance(stylesMapping, dict) and \
not isinstance(stylesMapping, UserDict):
raise PodError(MAPPING_NOT_DICT)
for xhtmlStyleName, odtStyleName in stylesMapping.iteritems():
if not isinstance(xhtmlStyleName, basestring):
for xhtmlStyleName, odtStyleName in stylesMapping.items():
if not isinstance(xhtmlStyleName, str):
raise PodError(MAPPING_ELEM_NOT_STRING)
if (xhtmlStyleName == 'h*') and \
not isinstance(odtStyleName, int):
raise PodError(MAPPING_OUTLINE_DELTA_NOT_INT)
if (xhtmlStyleName != 'h*') and \
not isinstance(odtStyleName, basestring):
not isinstance(odtStyleName, str):
raise PodError(MAPPING_ELEM_NOT_STRING)
if (xhtmlStyleName != 'h*') and \
((not xhtmlStyleName) or (not odtStyleName)):
@ -278,7 +283,7 @@ class StylesManager:
if xhtmlStyleName != 'h*':
odtStyle = self.styles.getStyle(odtStyleName)
if not odtStyle:
if self.podSpecificStyles.has_key(odtStyleName):
if odtStyleName in self.podSpecificStyles:
odtStyle = self.podSpecificStyles[odtStyleName]
else:
raise PodError(STYLE_NOT_FOUND % odtStyleName)
@ -311,7 +316,7 @@ class StylesManager:
This method returns True if p_attrs contains the winning (name,value)
pairs that match those in p_matchingAttrs. Note that ALL attrs in
p_matchingAttrs must be present in p_attrs.'''
for name, value in matchingAttrs.iteritems():
for name, value in matchingAttrs.items():
if name not in attrs: return
if value != attrs[name]: return
return True
@ -356,29 +361,29 @@ class StylesManager:
'''
res = None
cssStyleName = None
if attrs and attrs.has_key('class'):
if attrs and 'class' in attrs:
cssStyleName = attrs['class']
if classValue:
cssStyleName = classValue
# (1)
if localStylesMapping.has_key(cssStyleName):
if cssStyleName in localStylesMapping:
res = localStylesMapping[cssStyleName]
# (2)
if (not res) and localStylesMapping.has_key(elem):
if (not res) and elem in localStylesMapping:
styles = localStylesMapping[elem]
res = self.getStyleFromMapping(elem, attrs, styles)
# (3)
if (not res) and self.stylesMapping.has_key(cssStyleName):
if (not res) and cssStyleName in self.stylesMapping:
res = self.stylesMapping[cssStyleName]
# (4)
if (not res) and self.stylesMapping.has_key(elem):
if (not res) and elem in self.stylesMapping:
styles = self.stylesMapping[elem]
res = self.getStyleFromMapping(elem, attrs, styles)
# (5)
if (not res) and self.styles.has_key(cssStyleName):
if (not res) and cssStyleName in self.styles:
res = self.styles[cssStyleName]
# (6)
if (not res) and self.podSpecificStyles.has_key(cssStyleName):
if (not res) and cssStyleName in self.podSpecificStyles:
res = self.podSpecificStyles[cssStyleName]
# (7)
if not res:
@ -386,9 +391,9 @@ class StylesManager:
if elem in XHTML_HEADINGS:
# Is there a delta that must be taken into account ?
outlineDelta = 0
if localStylesMapping.has_key('h*'):
if 'h*' in localStylesMapping:
outlineDelta += localStylesMapping['h*']
elif self.stylesMapping.has_key('h*'):
elif 'h*' in self.stylesMapping:
outlineDelta += self.stylesMapping['h*']
outlineLevel = int(elem[1]) + outlineDelta
# Normalize the outline level

View file

@ -38,7 +38,7 @@ class AnnotationsRemover(OdfParser):
machine-specific info, like absolute paths to the python files, etc.'''
def __init__(self, env, caller):
OdfParser.__init__(self, env, caller)
self.res = u''
self.res = ''
self.inAnnotation = False # Are we parsing an annotation ?
self.textEncountered = False # Within an annotation, have we already
# met a text ?
@ -58,7 +58,7 @@ class AnnotationsRemover(OdfParser):
self.ignore = True
if not self.ignore:
self.res += '<%s' % elem
for attrName, attrValue in attrs.items():
for attrName, attrValue in list(attrs.items()):
self.res += ' %s="%s"' % (attrName, attrValue)
self.res += '>'
def endElement(self, elem):
@ -93,12 +93,12 @@ class Test(appy.shared.test.Test):
if not os.path.exists(contextPy):
raise TesterError(CONTEXT_NOT_FOUND % contextPy)
contextPkg = 'appy.pod.test.contexts.%s' % contextName
exec 'import %s' % contextPkg
exec 'context = dir(%s)' % contextPkg
exec('import %s' % contextPkg)
exec('context = dir(%s)' % contextPkg)
res = {}
for elem in context:
if not elem.startswith('__'):
exec 'res[elem] = %s.%s' % (contextPkg, elem)
exec('res[elem] = %s.%s' % (contextPkg, elem))
return res
def do(self):

View file

@ -1,6 +1,6 @@
class Student:
def __init__(self, **kwargs):
for k, v in kwargs.iteritems():
for k, v in kwargs.items():
setattr(self, k, v)
students = [

View file

@ -47,7 +47,7 @@ class HtmlElement:
# but for a strange reason those attrs are back to None (probably for
# performance reasons they become inaccessible after a while).
self.classAttr = None
if attrs.has_key('class'):
if 'class' in attrs:
self.classAttr = attrs['class']
self.tagsToReopen = [] # When the HTML element corresponding to self
# is completely dumped, if there was a problem related to tags
@ -58,7 +58,7 @@ class HtmlElement:
# to self, we may need to close other tags (ie closing a paragraph
# before closing a cell). This list contains HtmlElement instances.
self.elemType = self.elem
if self.elemTypes.has_key(self.elem):
if self.elem in self.elemTypes:
self.elemType = self.elemTypes[self.elem]
# If a conflict occurs on this element, we will note it.
self.isConflictual = False
@ -71,7 +71,7 @@ class HtmlElement:
def getOdfTag(self, env):
'''Gets the raw ODF tag that corresponds to me'''
res = ''
if HTML_2_ODT.has_key(self.elem):
if self.elem in HTML_2_ODT:
res += '%s:%s' % (env.textNs, HTML_2_ODT[self.elem])
elif self.elem == 'a':
res += '%s:a' % env.textNs
@ -216,8 +216,8 @@ class HtmlTable:
elems = str(time.time()).split('.')
self.name= 'AppyTable%s%s%d' % (elems[0],elems[1],random.randint(1,100))
self.styleNs = env.ns[OdfEnvironment.NS_STYLE]
self.res = u'' # The sub-buffer
self.tempRes = u'' # The temporary sub-buffer, into which we will
self.res = '' # The sub-buffer
self.tempRes = '' # The temporary sub-buffer, into which we will
# dump all table sub-elements, until we encounter the end of the first
# row. Then, we will know how much columns are defined in the table;
# we will dump columns declarations into self.res and dump self.tempRes
@ -294,8 +294,8 @@ class XhtmlEnvironment(XmlEnvironment):
XmlEnvironment.__init__(self)
self.renderer = renderer
self.ns = renderer.currentParser.env.namespaces
self.res = u''
self.currentContent = u''
self.res = ''
self.currentContent = ''
self.currentElements = [] # Stack of currently walked elements
self.currentLists = [] # Stack of currently walked lists (ul or ol)
self.currentTables = [] # Stack of currently walked tables
@ -349,7 +349,7 @@ class XhtmlEnvironment(XmlEnvironment):
# Dump and reinitialize the current content
contentSize = len(self.currentContent)
self.dumpString(escapeXml(self.currentContent))
self.currentContent = u''
self.currentContent = ''
# If we are within a table cell, update the total size of cell content
if not contentSize: return
if self.currentTables and self.currentTables[-1].inCell:
@ -363,7 +363,7 @@ class XhtmlEnvironment(XmlEnvironment):
styleName = None
if odtStyle:
styleName = odtStyle.name
elif DEFAULT_ODT_STYLES.has_key(htmlElem.elem):
elif htmlElem.elem in DEFAULT_ODT_STYLES:
styleName = DEFAULT_ODT_STYLES[htmlElem.elem]
res = ''
if styleName:
@ -458,7 +458,7 @@ class XhtmlEnvironment(XmlEnvironment):
elif elem in TABLE_CELL_TAGS:
# Determine colspan
colspan = 1
if attrs.has_key('colspan'): colspan = int(attrs['colspan'])
if 'colspan' in attrs: colspan = int(attrs['colspan'])
table = self.currentTables[-1]
table.inCell = colspan
table.cellIndex += colspan
@ -503,7 +503,7 @@ class XhtmlEnvironment(XmlEnvironment):
table.res+= '<%s:table-column %s:style-name="%s.%d"/>' % \
(self.tableNs, self.tableNs, table.name, i)
table.res += table.tempRes
table.tempRes = u''
table.tempRes = ''
elif elem in TABLE_CELL_TAGS:
# Update attr "columnContentSizes" of the currently parsed table,
# excepted if the cell spans several columns.
@ -535,7 +535,7 @@ class XhtmlParser(XmlParser):
resAttrs = attrs
if attrs:
resAttrs = {}
for attrName in attrs.keys():
for attrName in list(attrs.keys()):
resAttrs[attrName.lower()] = attrs[attrName]
if attrs == None:
return resElem
@ -548,11 +548,11 @@ class XhtmlParser(XmlParser):
currentElem = e.onElementStart(elem, attrs)
odfTag = currentElem.getOdfTag(e)
if HTML_2_ODT.has_key(elem):
if elem in HTML_2_ODT:
e.dumpStyledElement(currentElem, odfTag, attrs)
elif elem == 'a':
e.dumpString('<%s %s:type="simple"' % (odfTag, e.linkNs))
if attrs.has_key('href'):
if 'href' in attrs:
e.dumpString(' %s:href="%s"' % (e.linkNs,
escapeXml(attrs['href'])))
e.dumpString('>')
@ -577,13 +577,13 @@ class XhtmlParser(XmlParser):
elif elem in TABLE_CELL_TAGS:
e.dumpString('<%s %s:style-name="%s"' % \
(odfTag, e.tableNs, DEFAULT_ODT_STYLES[elem]))
if attrs.has_key('colspan'):
if 'colspan' in attrs:
e.dumpString(' %s:number-columns-spanned="%s"' % \
(e.tableNs, attrs['colspan']))
e.dumpString('>')
elif elem == 'img':
style = None
if attrs.has_key('style'): style = attrs['style']
if 'style' in attrs: style = attrs['style']
imgCode = e.renderer.importDocument(at=attrs['src'],
wrapInPara=False, style=style)
e.dumpString(imgCode)