Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore/python3 #2

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion excel_handler/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from handler import ExcelHandler
from __future__ import absolute_import
from .handler import ExcelHandler
assert ExcelHandler

version = "0.2.3"
15 changes: 9 additions & 6 deletions excel_handler/fields.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from builtins import str
from past.builtins import basestring
from builtins import object
import xlrd
import datetime

Expand Down Expand Up @@ -46,16 +49,16 @@ def cast(self, value, book, row_data):
except:
try:
return self.choices_inv[value]
except ValueError, error:
except ValueError as error:
error.args += (self.name,)
raise ValueError(error)
except KeyError, error:
except KeyError as error:
error.args += (self.name,)
raise KeyError(error)

try:
return self.cast_method(value)
except ValueError, error:
except ValueError as error:
error.args += (self.name, value)
raise ValueError(error)

Expand All @@ -69,12 +72,12 @@ def write(self, workbook, sheet, row, value):
if self.choices:
try:
value = self.choices[value]
except KeyError, error:
except KeyError as error:
if value is not None:
raise KeyError(error)

if hasattr(value, 'translate'):
value = unicode(value)
value = str(value)

sheet.write(row, self.col, value)

Expand Down Expand Up @@ -104,7 +107,7 @@ def __init__(self, col, *args, **kwargs):
class CharField(Field):
def __init__(self, col, *args, **kwargs):
super(CharField, self).__init__(col, *args, **kwargs)
self.cast_method = unicode
self.cast_method = str


class DateTimeField(Field):
Expand Down
29 changes: 16 additions & 13 deletions excel_handler/handler.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
""" This document defines the excel_handler module """
from __future__ import print_function
from __future__ import absolute_import
from builtins import str
from builtins import object
import xlrd
import xlsxwriter
import datetime
from fields import Field
from .fields import Field

from collections import namedtuple
from future.utils import with_metaclass


class FieldNotFound(Exception):
Expand All @@ -27,7 +32,7 @@ def __new__(cls, name, bases, attrs):

cols = {}

for k, v in attrs.items():
for k, v in list(attrs.items()):
if isinstance(v, Field):
field = attrs.pop(k)
field.name = k
Expand All @@ -47,7 +52,7 @@ def __new__(cls, name, bases, attrs):

attrs['fieldname_to_field'] = fieldname_to_field
attrs['fields'] = sorted(
fieldname_to_field.values(),
list(fieldname_to_field.values()),
key=lambda field: field.col
)

Expand All @@ -56,7 +61,7 @@ def __new__(cls, name, bases, attrs):
this = sup.__new__(cls, name, bases, attrs)
field_count = len(fieldname_to_field)

for field_name, field in fieldname_to_field.items():
for field_name, field in list(fieldname_to_field.items()):
try:
if field._distance_from_last < 0:
field.col = field_count + field._distance_from_last
Expand All @@ -66,12 +71,10 @@ def __new__(cls, name, bases, attrs):
return this


class ExcelHandler():
class ExcelHandler(with_metaclass(ExcelHandlerMetaClass, object)):
""" ExcelHandler is a class that is used to wrap common operations in
excel files """

__metaclass__ = ExcelHandlerMetaClass

def __init__(self, path=None, excel_file=None, mode='r', on_demand=False):
if path is None and excel_file is None:
raise Exception("path or excel_file requried")
Expand Down Expand Up @@ -224,7 +227,7 @@ def read(self, skip_titles=False, failfast=False, ignore_blank_rows=True,
if not err.args:
err.args = ('', )
msg = u'Cannot read row "{}" : Column {}, {}'.format(
row + 1, unicode(field.verbose_name), err.args[0])
row + 1, str(field.verbose_name), err.args[0])
err.args = (msg,) + err.args[1:]
if failfast:
raise
Expand All @@ -240,7 +243,7 @@ def read(self, skip_titles=False, failfast=False, ignore_blank_rows=True,
)
)
else:
print msg
print(msg)
continue_while = True
break

Expand Down Expand Up @@ -333,22 +336,22 @@ def write(self, data, set_titles=False):
formt = self.workbook.add_format()
self.set_title_format(formt)

for field_name, field in self.fieldname_to_field.items():
for field_name, field in list(self.fieldname_to_field.items()):
self.sheet.write(
0,
field.col,
unicode(field.verbose_name),
str(field.verbose_name),
formt
)
row = 1

# set format and prepare the write for each field
for field_name, field in self.fieldname_to_field.items():
for field_name, field in list(self.fieldname_to_field.items()):
field.set_column_format(self)
field.prepare_write()

for row_data in data:
for field_name, value in row_data.items():
for field_name, value in list(row_data.items()):
try:
field = self.fieldname_to_field[field_name]
except KeyError:
Expand Down
2 changes: 2 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@
# 'mimeparse',
'xlutils(>=1.6.0)',
'XlsxWriter(>=0.5.7)',
'future(>=0.18.2)',
],
install_requires=[
'xlutils >= 1.6.0',
'XlsxWriter >= 0.5.7',
'future >=0.18.2',
],
package_data={
},
Expand Down
25 changes: 13 additions & 12 deletions test/test.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from builtins import object
from excel_handler import ExcelHandler
from excel_handler import fields

import unittest
import datetime


class Query:
class Query(object):
def values_list(*args, **kwargs):
return [(
'one', 1
Expand All @@ -16,13 +17,13 @@ def values_list(*args, **kwargs):
)]


class Meta:
class Meta(object):
object_name = 'model'


class Model():
class Model(object):

class Objects:
class Objects(object):
def all(self):
return Query()

Expand Down Expand Up @@ -128,10 +129,10 @@ def test_read_rows(self):
self.assertEqual(len(second_row), 2)
self.assertEqual(len(second_row[0]), 4)

for key, value in data[0].items():
for key, value in list(data[0].items()):
self.assertEqual(first_row[0][key], value)

for key, value in data[1].items():
for key, value in list(data[1].items()):
self.assertEqual(second_row[0][key], value)

def test_write_rows(self):
Expand Down Expand Up @@ -160,7 +161,7 @@ def test_read(self):

self.assertEqual(len(expected_data), len(data))
for i, obj in enumerate(expected_data):
for k, expected_value in obj.items():
for k, expected_value in list(obj.items()):
read_value = data[i][k]
self.assertEqual(read_value, expected_value)

Expand All @@ -185,7 +186,7 @@ def test_read(self):

self.assertEqual(len(expected_data), len(data))
for i, obj in enumerate(expected_data):
for k, expected_value in obj.items():
for k, expected_value in list(obj.items()):
read_value = data[i][k]
self.assertEqual(read_value, expected_value)

Expand All @@ -207,7 +208,7 @@ def test_read_empty(self):

self.assertEqual(len(expected_data), len(data))
for i, obj in enumerate(expected_data):
for k, expected_value in obj.items():
for k, expected_value in list(obj.items()):
read_value = data[i][k]
self.assertEqual(read_value, expected_value)

Expand Down Expand Up @@ -252,7 +253,7 @@ def test_read(self):

self.assertEqual(len(expected_data), len(data))
for i, obj in enumerate(expected_data):
for k, expected_value in obj.items():
for k, expected_value in list(obj.items()):
read_value = data[i][k]
self.assertEqual(read_value, expected_value)

Expand Down Expand Up @@ -290,7 +291,7 @@ def test_write(self):
self.assertEqual(len(in_data), 3)

for i, obj in enumerate(data):
for k, v in obj.items():
for k, v in list(obj.items()):
self.assertEqual(in_data[i][k], v)

# testing the choices valus
Expand Down Expand Up @@ -339,7 +340,7 @@ def test_read(self):

self.assertEqual(len(expected_data), len(data))
for i, obj in enumerate(expected_data):
for k, expected_value in obj.items():
for k, expected_value in list(obj.items()):
read_value = data[i][k]
self.assertEqual(read_value, expected_value)

Expand Down