Misc. cleanup for Python 3

This commit is contained in:
Lance Edgar 2018-02-12 14:41:40 -06:00
parent 189bc1faa8
commit ee35cc6f22
24 changed files with 49 additions and 36 deletions

View file

@ -153,7 +153,7 @@ class GridFilter(object):
self.default_active = default_active
self.default_verb = default_verb
self.default_value = default_value
for key, value in kwargs.iteritems():
for key, value in kwargs.items():
setattr(self, key, value)
def __repr__(self):
@ -369,7 +369,7 @@ class AlchemyByteStringFilter(AlchemyStringFilter):
def get_value(self, value=UNSPECIFIED):
value = super(AlchemyByteStringFilter, self).get_value(value)
if isinstance(value, unicode):
if isinstance(value, six.text_type):
value = value.encode(self.value_encoding)
return value
@ -415,7 +415,7 @@ class AlchemyNumericFilter(AlchemyGridFilter):
# term for integer field...
def value_invalid(self, value):
return bool(value and len(unicode(value)) > 8)
return bool(value and len(six.text_type(value)) > 8)
def filter_equal(self, query, value):
if self.value_invalid(value):

View file

@ -5,7 +5,7 @@
<h2>${project_title} ${project_version}</h2>
% for name, version in packages.iteritems():
% for name, version in packages.items():
<h3>${name} ${version}</h3>
% endfor

View file

@ -39,7 +39,7 @@
## % endif
% if request.user:
${form.field_div('user_name', form.hidden('user_name', value=unicode(request.user)) + unicode(request.user), label="Your Name")}
${form.field_div('user_name', form.hidden('user_name', value=six.text_type(request.user)) + six.text_type(request.user), label="Your Name")}
% else:
${form.field_div('user_name', form.text('user_name'), label="Your Name")}
% endif

View file

@ -30,7 +30,7 @@
${h.form(request.current_route_url())}
${h.csrf_token(request)}
% for name, display in printer.required_settings.iteritems():
% for name, display in printer.required_settings.items():
<div class="field-wrapper">
<label for="${name}">${display}</label>
<div class="field">

View file

@ -31,7 +31,7 @@ ${parent.body()}
<h2>Printer Settings</h2>
<div class="form">
% for name, display in printer.required_settings.iteritems():
% for name, display in printer.required_settings.items():
<div class="field-wrapper">
<label>${display}</label>
<div class="field">${instance.get_printer_setting(name) or ''}</div>

View file

@ -8,7 +8,7 @@
var recipient_mappings = new Map([
<% last = len(available_recipients) %>
% for i, (uuid, entry) in enumerate(sorted(available_recipients.iteritems(), key=lambda r: r[1]), 1):
% for i, (uuid, entry) in enumerate(sorted(available_recipients.items(), key=lambda r: r[1]), 1):
['${uuid}', ${json.dumps(entry)|n}]${',' if i < last else ''}
% endfor
]);

View file

@ -5,7 +5,7 @@
<h2>${project_title} ${project_version}</h2>
% for name, version in packages.iteritems():
% for name, version in packages.items():
<h3>${name} ${version}</h3>
% endfor

View file

@ -241,7 +241,7 @@
</tr>
</thead>
<tbody>
% for emp in sorted(employees, key=unicode):
% for emp in sorted(employees, key=six.text_type):
<tr data-employee-uuid="${emp.uuid}">
<td class="employee">
## TODO: add link to single employee schedule / timesheet here...

View file

@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
# -*- coding: utf-8; -*-
################################################################################
#
# Rattail -- Retail Software Framework
# Copyright © 2010-2017 Lance Edgar
# Copyright © 2010-2018 Lance Edgar
#
# This file is part of Rattail.
#
@ -26,7 +26,9 @@ Tween Factories
from __future__ import unicode_literals, absolute_import
import six
from sqlalchemy.exc import OperationalError
from transaction.interfaces import TransientError
@ -51,7 +53,7 @@ def sqlerror_tween_factory(handler, registry):
response = handler(request)
except OperationalError as error:
if error.connection_invalidated:
raise TransientError(str(error))
raise TransientError(six.text_type(error))
raise
return response

View file

@ -2,7 +2,7 @@
################################################################################
#
# Rattail -- Retail Software Framework
# Copyright © 2010-2017 Lance Edgar
# Copyright © 2010-2018 Lance Edgar
#
# This file is part of Rattail.
#
@ -28,6 +28,7 @@ from __future__ import unicode_literals, absolute_import
import datetime
import six
import pytz
import humanize
@ -107,7 +108,7 @@ def raw_datetime(config, value):
if value.year >= 1900:
kwargs['c'] = value.strftime('%Y-%m-%d %I:%M:%S %p')
else:
kwargs['c'] = unicode(value)
kwargs['c'] = six.text_type(value)
# Avoid humanize error when calculating huge time diff.
if abs(time_ago.days) < 100000:

View file

@ -1148,7 +1148,7 @@ class FileBatchMasterView(BatchMasterView):
raise httpexceptions.HTTPNotFound()
path = batch.filepath(self.rattail_config)
response = FileResponse(path, request=self.request)
response.headers[b'Content-Length'] = str(os.path.getsize(path))
response.headers[b'Content-Length'] = six.binary_type(os.path.getsize(path))
filename = os.path.basename(batch.filename).encode('ascii', 'replace')
response.headers[b'Content-Disposition'] = b'attachment; filename="{}"'.format(filename)
return response

View file

@ -29,6 +29,8 @@ from __future__ import unicode_literals, absolute_import
import os
import datetime
import six
from rattail.db import model
from rattail.bouncer import get_handler
from rattail.bouncer.config import get_profile_keys
@ -175,7 +177,7 @@ class EmailBouncesView(MasterView):
handler = self.get_handler(bounce)
path = handler.msgpath(bounce)
response = FileResponse(path, request=self.request)
response.headers[b'Content-Length'] = str(os.path.getsize(path))
response.headers[b'Content-Length'] = six.binary_type(os.path.getsize(path))
response.headers[b'Content-Disposition'] = b'attachment; filename="bounce.eml"'
return response

View file

@ -2,7 +2,7 @@
################################################################################
#
# Rattail -- Retail Software Framework
# Copyright © 2010-2017 Lance Edgar
# Copyright © 2010-2018 Lance Edgar
#
# This file is part of Rattail.
#
@ -28,6 +28,8 @@ from __future__ import unicode_literals, absolute_import
import os
import six
from rattail.db import model
from rattail.util import progress_loop
@ -107,7 +109,7 @@ class View(object):
if not os.path.exists(path):
return self.notfound()
response = FileResponse(path, request=self.request)
response.headers[b'Content-Length'] = str(os.path.getsize(path))
response.headers[b'Content-Length'] = six.binary_type(os.path.getsize(path))
filename = os.path.basename(path).encode('ascii', 'replace')
response.headers[b'Content-Disposition'] = b'attachment; filename="{}"'.format(filename)
return response

View file

@ -248,7 +248,7 @@ class EmailPreview(View):
def email_template(self):
recipient = self.request.POST.get('recipient')
if recipient:
keys = filter(lambda k: k.startswith('send_'), self.request.POST.iterkeys())
keys = filter(lambda k: k.startswith('send_'), self.request.POST.keys())
key = keys[0][5:] if keys else None
if key:
email = mail.get_email(self.rattail_config, key)

View file

@ -144,7 +144,7 @@ class ExportMasterView(MasterView):
export = self.get_instance()
path = self.get_file_path(export)
response = FileResponse(path, request=self.request)
response.headers[b'Content-Length'] = str(os.path.getsize(path))
response.headers[b'Content-Length'] = six.binary_type(os.path.getsize(path))
response.headers[b'Content-Disposition'] = b'attachment; filename="{}"'.format(export.filename)
return response

View file

@ -199,7 +199,7 @@ class HandheldBatchView(FileBatchMasterView):
return text
def get_exec_options_kwargs(self, **kwargs):
kwargs['ACTION_OPTIONS'] = list(ACTION_OPTIONS.iteritems())
kwargs['ACTION_OPTIONS'] = list(ACTION_OPTIONS.items())
return kwargs
def get_execute_success_url(self, batch, result, **kwargs):

View file

@ -1200,7 +1200,7 @@ class MasterView(View):
"""
try:
index = int(self.request.GET['index'])
except KeyError, ValueError:
except (KeyError, ValueError):
return self.redirect(self.get_index_url())
if index < 1:
return self.redirect(self.get_index_url())

View file

@ -551,7 +551,7 @@ class ProductsView(MasterView):
if product and (not product.deleted or self.request.has_perm('products.view_deleted')):
data = {
'uuid': product.uuid,
'upc': unicode(product.upc),
'upc': six.text_type(product.upc),
'upc_pretty': product.upc.pretty(),
'full_description': product.full_description,
'image_url': pod.get_image_url(self.rattail_config, product.upc),
@ -770,8 +770,8 @@ def print_labels(request):
try:
printer.print_labels([(product, quantity, {})])
except Exception, error:
return {'error': str(error)}
except Exception as error:
return {'error': six.text_type(error)}
return {}

View file

@ -26,6 +26,8 @@ Views for "true" purchase orders
from __future__ import unicode_literals, absolute_import
import six
from rattail.db import model
from webhelpers2.html import HTML, tags
@ -133,7 +135,7 @@ class PurchaseView(MasterView):
if purchase.date_ordered:
return "{} (ordered {})".format(purchase.vendor, purchase.date_ordered.strftime('%Y-%m-%d'))
return "{} (ordered)".format(purchase.vendor)
return unicode(purchase)
return six.text_type(purchase)
def configure_grid(self, g):
super(PurchaseView, self).configure_grid(g)

View file

@ -2,7 +2,7 @@
################################################################################
#
# Rattail -- Retail Software Framework
# Copyright © 2010-2017 Lance Edgar
# Copyright © 2010-2018 Lance Edgar
#
# This file is part of Rattail.
#
@ -28,6 +28,8 @@ from __future__ import unicode_literals, absolute_import
import re
import six
import rattail
from rattail.db import model
from rattail.files import resource_path
@ -50,13 +52,13 @@ def get_upc(product):
UPC formatter. Strips PLUs to bare number, and adds "minus check digit"
for non-PLU UPCs.
"""
upc = unicode(product.upc)
upc = six.text_type(product.upc)
m = plu_upc_pattern.match(upc)
if m:
return unicode(int(m.group(1)))
return six.text_type(int(m.group(1)))
m = weighted_upc_pattern.match(upc)
if m:
return unicode(int(m.group(1)))
return six.text_type(int(m.group(1)))
return '{0}-{1}'.format(upc[:-1], upc[-1])

View file

@ -79,7 +79,7 @@ class ScheduleView(TimeSheetView):
# apply delete operations
deleted = []
for uuid, value in data['delete'].iteritems():
for uuid, value in data['delete'].items():
if value == 'delete':
shift = Session.query(model.ScheduledShift).get(uuid)
if shift:
@ -90,7 +90,7 @@ class ScheduleView(TimeSheetView):
created = {}
updated = {}
time_format = '%a %d %b %Y %I:%M %p'
for uuid, employee_uuid in data['start_time'].iteritems():
for uuid, employee_uuid in data['start_time'].items():
if uuid in deleted:
continue
if uuid.startswith('new-'):

View file

@ -81,7 +81,7 @@ class TimeSheetView(BaseTimeSheetView):
created = {}
updated = {}
time_format = '%a %d %b %Y %I:%M %p'
for uuid, time in data['start_time'].iteritems():
for uuid, time in data['start_time'].items():
if uuid in deleted:
continue
if uuid.startswith('new-'):

View file

@ -106,7 +106,7 @@ class VendorCatalogsView(FileBatchMasterView):
g.sorters['vendor'] = g.make_sorter(model.Vendor.name)
def get_instance_title(self, batch):
return unicode(batch.vendor)
return six.text_type(batch.vendor)
def configure_form(self, f):
super(VendorCatalogsView, self).configure_form(f)

View file

@ -26,6 +26,8 @@ Views for maintaining vendor invoices
from __future__ import unicode_literals, absolute_import
import six
from rattail.db import model, api
from rattail.vendors.invoices import iter_invoice_parsers, require_invoice_parser
@ -83,7 +85,7 @@ class VendorInvoicesView(FileBatchMasterView):
]
def get_instance_title(self, batch):
return unicode(batch.vendor)
return six.text_type(batch.vendor)
def configure_grid(self, g):
super(VendorInvoicesView, self).configure_grid(g)