Skip to content

Commit

Permalink
Python 3 compatibility
Browse files Browse the repository at this point in the history
- fix raise syntax
- fix except syntax
- use string methods instead of string module functions
- replace `dict.has_key(x)` with `x in dict`
- replace type tests with isinstance tests
  • Loading branch information
dataflake committed May 15, 2017
1 parent d8e206a commit 6cfd692
Show file tree
Hide file tree
Showing 11 changed files with 170 additions and 175 deletions.
34 changes: 16 additions & 18 deletions src/Shared/DC/ZRDB/Aqueduct.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@ def _argdata(self, REQUEST):
# to work as supposed to work.

# if missing:
# raise self.MissingArgumentError, \
# raise self.MissingArgumentError( \
# "The following arguments were omitted " \
# " from the ZSQL method call: %s" % str(missing)
# " from the ZSQL method call: %s" % str(missing))
#

return r
Expand Down Expand Up @@ -136,7 +136,7 @@ def manage_test(self, REQUEST):

def index_html(self, URL1):
" "
raise Redirect, ("%s/manage_testForm" % URL1)
raise Redirect("%s/manage_testForm" % URL1)

class Composite:

Expand All @@ -153,7 +153,7 @@ def _getquery(self,id):
except: pass
return q
except: pass
if i > 100: raise AttributeError, id
if i > 100: raise AttributeError(id)
i=i+1
o=o.aq_parent

Expand Down Expand Up @@ -252,7 +252,7 @@ def custom_default_report(id, result, action='', no_table=0,
for c in columns:
n=c['name']
if goofy(n) is not None:
n='expr="_[\'%s]"' % (`'"'+n`[2:])
n='expr="_[\'%s]"' % (repr('"'+n)[2:])
row.append(' %s<dtml-var %s%s>%s'
% (td,n,c['type']!='s' and ' null=""' or '',_td))

Expand Down Expand Up @@ -294,7 +294,7 @@ def custom_default_zpt_report(id, result, action='', no_table=0,


def detypify(arg):
l=string.find(arg,':')
l=arg.find(':')
if l > 0: arg=arg[:l]
return arg

Expand Down Expand Up @@ -372,7 +372,7 @@ def parse(text,
l = len(mo.group(1))
else:
if not text or not text.strip(): return Args(result,keys)
raise InvalidParameter, text
raise InvalidParameter(text)

lt=name.find(':')
if lt > 0:
Expand All @@ -399,8 +399,8 @@ def quotedHTML(text,
return text

def nicify(name):
name=string.replace(string.strip(name), '_',' ')
return string.upper(name[:1])+name[1:]
name=string.replace(name.strip(), '_',' ')
return name[:1].upper() + name[1:]

def decapitate(html, RESPONSE=None,
header_re=re.compile(
Expand All @@ -420,7 +420,7 @@ def decapitate(html, RESPONSE=None,

headers, html = mo.group(1,3)

headers=string.split(headers,'\n')
headers=headers.split('\n')

i=1
while i < len(headers):
Expand All @@ -439,9 +439,9 @@ def decapitate(html, RESPONSE=None,
mo = name_re.match(headers[i])
if mo:
k,v = mo.group(1,2)
v=string.strip(v)
v = v.strip()
else:
raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i])
raise ValueError('Invalid Header (%d): %s ' % (i,headers[i]))
RESPONSE.setHeader(k,v)

return html
Expand All @@ -452,11 +452,9 @@ def delimited_output(results,REQUEST,RESPONSE):
try: output_type=REQUEST['output-type']
except: output_type='text/plain'
RESPONSE.setHeader('content-type', output_type)
join=string.join
return "%s\n%s\n" % (
join(results.names(),delim),
join(map(lambda row, delim=delim, join=join:
join(map(str,row),delim),
results),
'\n')
delim.join(results.names()),
'\n'.join(map(lambda row, delim=delim:
delim.join(map(str,row)),
results)),
)
20 changes: 10 additions & 10 deletions src/Shared/DC/ZRDB/Connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@
from AccessControl.Role import RoleManager


from Aqueduct import custom_default_report
import RDB
from Results import Results
from .Aqueduct import custom_default_report
from . import RDB
from .Results import Results

LOG = getLogger('ZRDB.Connection')

Expand Down Expand Up @@ -193,7 +193,7 @@ def __call__(self, v=None):
if s:
self.connect(s)
return self._v_database_connection
raise BadRequest,(
raise BadRequest(
'''The database connection is not connected''')

def connect(self,s):
Expand All @@ -204,20 +204,20 @@ def connect(self,s):
self._v_database_connection=DB(s)
except:
t, v, tb = sys.exc_info()
raise BadRequest, (
raise BadRequest(
'<strong>Error connecting to DB.</strong><br>\n'
'<!--\n%s\n%s\n-->\n'
% (t,v)), tb
% (t,v)).with_traceback(tb)
finally: tb=None
self._v_connected=DateTime()

return self

def sql_quote__(self, v):
if string.find(v,"\'") >= 0:
v = string.join(string.split(v,"\'"),"''")
if string.find(v,"\x00") >= 0:
v = string.join(string.split(v,"\x00"), "")
if v.find("\'") >= 0:
v = "''".join(v.split("\'"))
if v.find("\x00") >= 0:
v = "".join(v.split("\x00"))
return "'%s'" % v

InitializeClass(Connection)
52 changes: 26 additions & 26 deletions src/Shared/DC/ZRDB/DA.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,15 @@
except ImportError:
from AccessControl.Role import RoleManager

from Aqueduct import BaseQuery
from Aqueduct import custom_default_report
from Aqueduct import default_input_form
from Aqueduct import parse
from RDB import File
from Results import Results
from sqlgroup import SQLGroup
from sqltest import SQLTest
from sqlvar import SQLVar
from .Aqueduct import BaseQuery
from .Aqueduct import custom_default_report
from .Aqueduct import default_input_form
from .Aqueduct import parse
from .RDB import File
from .Results import Results
from .sqlgroup import SQLGroup
from .sqltest import SQLTest
from .sqlvar import SQLVar


def _getPath(home, prefix, name, suffixes):
Expand Down Expand Up @@ -221,7 +221,7 @@ def getObject(module, name, reload=0,
raise NotFound("The specified module, '%s', "
"couldn't be opened." % module)
module_dict = {}
exec execsrc in module_dict
exec(execsrc, module_dict)

if old is not None:
# XXX Accretive??
Expand Down Expand Up @@ -371,12 +371,12 @@ def manage_edit(self,title,connection_id,arguments,template,
SQL Template.
"""

if self._size_changes.has_key(SUBMIT):
if SUBMIT in self._size_changes:
return self._er(title,connection_id,arguments,template,
SUBMIT,dtpref_cols,dtpref_rows,REQUEST)

if self.wl_isLocked():
raise ResourceLockedError, 'SQL Method is locked via WebDAV'
raise ResourceLockedError('SQL Method is locked via WebDAV')

self.title=str(title)
self.connection_id=str(connection_id)
Expand Down Expand Up @@ -517,8 +517,8 @@ def manage_test(self, REQUEST):
try:
try:
src, result=self(REQUEST, test__=1)
if string.find(src,'\0'):
src=string.join(string.split(src,'\0'),'\n'+'-'*60+'\n')
if src.find('\0'):
src= ('\n'+'-'*60+'\n').join(src.split('\0'))
if result._searchable_result_columns():
r=custom_default_report(self.id, result)
else:
Expand Down Expand Up @@ -597,7 +597,7 @@ def _cached_result(self, DB__, query, max_rows, conn_id):
del keys[0]

# okay, now see if we have a cached result
if cache.has_key(cache_key):
if cache_key in cache:
k, r = cache[cache_key]
# the result may still be stale, as we only hoover out
# stale results above if the cache gets too large.
Expand Down Expand Up @@ -671,13 +671,13 @@ def __call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw):
try:
dbc=getattr(self, c)
except AttributeError:
raise AttributeError, (
raise AttributeError(
"The database connection <em>%s</em> cannot be found." % (
c))

try:
DB__=dbc()
except: raise DatabaseError, (
except: raise DatabaseError(
'%s is not connected to a database' % self.id)

if hasattr(self, 'aq_parent'):
Expand All @@ -693,10 +693,10 @@ def __call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw):
security.addContext(self)
try:
try:
query=apply(self.template, (p,), argdata)
except TypeError, msg:
query=self.template(p, **argdata)
except TypeError as msg:
msg = str(msg)
if string.find(msg,'client') >= 0:
if msg.find('client') >= 0:
raise NameError("'client' may not be used as an " +
"argument name in this context")
else: raise
Expand Down Expand Up @@ -741,8 +741,8 @@ def __getitem__(self, key):
if self.allow_simple_one_argument_traversal and len(args)==1:
results=self({args.keys()[0]: key})
if results:
if len(results) > 1: raise KeyError, key
else: raise KeyError, key
if len(results) > 1: raise KeyError(key)
else: raise KeyError(key)
r=results[0]
# if hasattr(self, 'aq_parent'): r=r.__of__(self.aq_parent)
return r
Expand Down Expand Up @@ -795,8 +795,8 @@ def __bobo_traverse__(self, REQUEST, key):
if results:
if len(results) > 1:
try: return results[string.atoi(key)].__of__(da)
except: raise KeyError, key
else: raise KeyError, key
except: raise KeyError(key)
else: raise KeyError(key)
r=results[0]
# if hasattr(da, 'aq_parent'): r=r.__of__(da.aq_parent)
self._r=r
Expand All @@ -808,8 +808,8 @@ def __bobo_traverse__(self, REQUEST, key):
except: pass

try: return getattr(r,key)
except AttributeError, v:
if str(v) != key: raise AttributeError, v
except AttributeError as v:
if str(v) != key: raise AttributeError(v)

return r[key]

Expand Down
40 changes: 21 additions & 19 deletions src/Shared/DC/ZRDB/RDB.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,16 @@ def parse_text(s):
return '\\'.join(r)


Parsers = {
'n': string.atof,
'i': string.atoi,
'l': string.atol,
'd': DateTime,
't': parse_text,
}
if six.PY3:
long = int

Parsers={'n': float,
'i': int,
'l': long,
'd': DateTime,
't': parse_text,
}


class SQLAlias(Base):

Expand Down Expand Up @@ -75,17 +78,17 @@ def __init__(self, file, brains=NoBrains, parent=None, zbrains=NoBrains):
line = line[:-1]
self._names = names = [name.strip() for name in line.split('\t')]
if not names:
raise ValueError, 'No column names'
raise ValueError('No column names')

aliases = []
self._schema = schema = {}
i = 0
for name in names:
if not name:
raise ValueError, 'Empty column name, %s' % name
raise ValueError('Empty column name, %s' % name)

if schema.has_key(name):
raise ValueError, 'Duplicate column name, %s' % name
if name in schema:
raise ValueError('Duplicate column name, %s' % name)

schema[name] = i
i = i + 1
Expand All @@ -107,10 +110,10 @@ def __init__(self, file, brains=NoBrains, parent=None, zbrains=NoBrains):
self._defs = defs = [_def.strip() for _def in line.split('\t')]

if not defs:
raise ValueError, 'No column definitions'
raise ValueError('No column definitions')

if len(defs) != nv:
raise ValueError, (
raise ValueError(
"""The number of column names and the number of column
definitions are different.""")

Expand All @@ -121,21 +124,20 @@ def __init__(self, file, brains=NoBrains, parent=None, zbrains=NoBrains):
self.__items__ = items = []

for _def in defs:

if not _def:
raise ValueError, ('Empty column definition for %s' % names[i])
raise ValueError('Empty column definition for %s' % names[i])

mo = defre.match(_def)
if mo is None:
raise ValueError, (
raise ValueError(
'Invalid column definition for, %s, for %s'
% _def, names[i])

type = mo.group(2).lower()
width = mo.group(1)

if width:
width = string.atoi(width)
width = int(width)
else:
width = 8

Expand Down Expand Up @@ -207,7 +209,7 @@ def __getitem__(self,index):
if l < nv:
fields = fields+['']*(nv-l)
else:
raise ValueError, (
raise ValueError(
"""The number of items in record %s is invalid
<pre>%s\n%s\n%s\n%s</pre>
"""
Expand All @@ -217,7 +219,7 @@ def __getitem__(self,index):
v = parser(fields[i])
except:
if fields[i]:
raise ValueError, (
raise ValueError(
"""Invalid value, %s, for %s in record %s"""
% (fields[i], self._names[i], index))
else:
Expand Down

0 comments on commit 6cfd692

Please sign in to comment.