diff options
| author | James Douglass <jamesdouglassusa@gmail.com> | 2014-05-30 17:27:59 -0700 |
|---|---|---|
| committer | James Douglass <jamesdouglassusa@gmail.com> | 2014-08-21 22:06:42 -0700 |
| commit | a21f8187f8bdbe27434478da45fa58f3e2158268 (patch) | |
| tree | 25c0a36283bdec214c5629459040a26f84924ba1 /tablib/packages/dbfpy/utils.py | |
| parent | 8479df725e1e02e4380acaba2cf93a74ca63b84f (diff) | |
| download | tablib-a21f8187f8bdbe27434478da45fa58f3e2158268.tar.gz | |
Adding DBF support.
Squashing two squashes.
Adding DBF support
Adding the DBFpy python package
The DBFpy package provides basic dbf support for python. Still need to
write an interface format file for tablib.
Adding DBF format and imports in compat.py
Adding DBF format to formats.__init__
DBF format had not been committed to formats.__init__, so I’m adding it.
Adding a dbf import test
Adding at test to check whether a DBF can be created properly and
compare it against a regression binary string.
Adding an import_set test (and renaming another)
Adding an import_set test that conforms with the other import_set tests
for other formats. I’m also adding an export_set function.
Fixing system site-packages import
Importing dbfpy from tab lib.packages instead of system site packages.
Fixing a syntaxError in dbfpy/dbfnew.py
Fixing an issue with ending field definitions
DBFPY, when writing a DBF, terminates the field definitions with a
newline character. When importing a DBF from a stream, however, DBFPY
was looking only for the \x0D character rather than the newline. Now
we consider both cases.
Adding a test for dbf format detection
Adding DBF filetype detection tests
Adding tests for YAML, JSON, TSV, CSV using the DBF detection function.
Handling extra exceptions in dbf detection
Adding exception handling for struct.error, an exception that DBFPY
raises when trying to unpack a TSV table. Since it’s not a DBF file,
we know it’s not a DBF and return False.
Fixing an issue with the DBF set exporting test
The DBF set export test needed a bit enabled (probably the writeable
bit?) before the test would match the regression output.
Updating dbf interface
Updating the int/float class/type checking in the dbf format file.
This allows for python2 and python3 compatibility.
Tweaking dbfpy to work with python3
Altering a couple of imports.
Updating dbf tests for binary data compatibility
Making regression strings binary and improving debug messages for dbf
assertion errors.
Improving file handling for python 2 and 3
Updating DBF file handling for both python 2 and 3 in the _dbf
interface.
Adding a (seemingly) functional dbfpy for python3
I’ve made dbfpy python3 compatible! Tests appear to pass.
A significant change was made to the format detection test whereby I
made the input string a binary (bytes) string. If the string is not a
bytes string by the time we try to detect the format, we try to decode
the string as utf-8 (which admittedly might not be the safest thing to
do) and try to decode anyways.
Updating imports for tablib dbf interface
Now importing python2 or python3 versions as appropriate.
Updating dbf package references in compat.py
Cleaning up debugging print statements
Updating stream handling in dbf interface
Factoring the open() call out of the py3 conditional and removing the
temp file before returning the stream value.
Adding dbfpy3 init.py
I had apparently missed the dbfpy3 init file when committing dbfpy3.
Adding dbfpy and dbfpy3 to setup.py's package list
Switching test order of formats
Putting dbf format testing ahead of TSV. In some of my tests with
numeric DBF files, I encountered an issue where the ASCII horizontal
tab character (0x09) would appear in a numeric DBF. Because of the
order of tabular format imports, though, format detection would
recognize it as a TSV and not as a DBF.
Adding my name to AUTHORS.
Adding a DBF property to tab lib core
Documentation includes examples on how to explicitly load a DBF
straight from a file and how to load a DBF from a binary string. Also,
how to write the binary data to a file.
Adding DBF format notes to README
Adding exclamation point to DBF section title
Matching formatting of XLS section
Updating setup.py to match current dev state
Setup.py had been updated since I forked the tablib repo, so I’m
updating setup.py to match its current structure while still
maintaining DBF compatibility.
Fixed callable collumn test
the test was sending a list instead of a function
CORE CONTRIBUTORS
:cake: @iurisilvio
v0.10.0
WHEELS
3.3, 3.4
makefile for WHEELS
v0.10.0 history
ALL
Separate py2 and py3 packages to avoid installation errors. Fix #151
Running travis and tox with python 3.4.
Adding DBF support
Adding the DBFpy python package
The DBFpy package provides basic dbf support for python. Still need to
write an interface format file for tablib.
Adding DBF format and imports in compat.py
Adding DBF format to formats.__init__
DBF format had not been committed to formats.__init__, so I’m adding it.
Adding a dbf import test
Adding at test to check whether a DBF can be created properly and
compare it against a regression binary string.
Adding an import_set test (and renaming another)
Adding an import_set test that conforms with the other import_set tests
for other formats. I’m also adding an export_set function.
Fixing system site-packages import
Importing dbfpy from tab lib.packages instead of system site packages.
Fixing a syntaxError in dbfpy/dbfnew.py
Fixing an issue with ending field definitions
DBFPY, when writing a DBF, terminates the field definitions with a
newline character. When importing a DBF from a stream, however, DBFPY
was looking only for the \x0D character rather than the newline. Now
we consider both cases.
Adding a test for dbf format detection
Adding DBF filetype detection tests
Adding tests for YAML, JSON, TSV, CSV using the DBF detection function.
Handling extra exceptions in dbf detection
Adding exception handling for struct.error, an exception that DBFPY
raises when trying to unpack a TSV table. Since it’s not a DBF file,
we know it’s not a DBF and return False.
Fixing an issue with the DBF set exporting test
The DBF set export test needed a bit enabled (probably the writeable
bit?) before the test would match the regression output.
Updating dbf interface
Updating the int/float class/type checking in the dbf format file.
This allows for python2 and python3 compatibility.
Tweaking dbfpy to work with python3
Altering a couple of imports.
Updating dbf tests for binary data compatibility
Making regression strings binary and improving debug messages for dbf
assertion errors.
Improving file handling for python 2 and 3
Updating DBF file handling for both python 2 and 3 in the _dbf
interface.
Adding a (seemingly) functional dbfpy for python3
I’ve made dbfpy python3 compatible! Tests appear to pass.
A significant change was made to the format detection test whereby I
made the input string a binary (bytes) string. If the string is not a
bytes string by the time we try to detect the format, we try to decode
the string as utf-8 (which admittedly might not be the safest thing to
do) and try to decode anyways.
Updating imports for tablib dbf interface
Now importing python2 or python3 versions as appropriate.
Updating dbf package references in compat.py
Cleaning up debugging print statements
Updating stream handling in dbf interface
Factoring the open() call out of the py3 conditional and removing the
temp file before returning the stream value.
Adding dbfpy3 init.py
I had apparently missed the dbfpy3 init file when committing dbfpy3.
Adding dbfpy and dbfpy3 to setup.py's package list
Switching test order of formats
Putting dbf format testing ahead of TSV. In some of my tests with
numeric DBF files, I encountered an issue where the ASCII horizontal
tab character (0x09) would appear in a numeric DBF. Because of the
order of tabular format imports, though, format detection would
recognize it as a TSV and not as a DBF.
Adding my name to AUTHORS.
Adding a DBF property to tab lib core
Documentation includes examples on how to explicitly load a DBF
straight from a file and how to load a DBF from a binary string. Also,
how to write the binary data to a file.
Adding DBF format notes to README
Adding exclamation point to DBF section title
Matching formatting of XLS section
Updating setup.py to match current dev state
Setup.py had been updated since I forked the tablib repo, so I’m
updating setup.py to match its current structure while still
maintaining DBF compatibility.
Fixed callable collumn test
the test was sending a list instead of a function
CORE CONTRIBUTORS
:cake: @iurisilvio
v0.10.0
WHEELS
3.3, 3.4
makefile for WHEELS
v0.10.0 history
ALL
Separate py2 and py3 packages to avoid installation errors. Fix #151
Running travis and tox with python 3.4.
Diffstat (limited to 'tablib/packages/dbfpy/utils.py')
| -rw-r--r-- | tablib/packages/dbfpy/utils.py | 170 |
1 files changed, 170 insertions, 0 deletions
diff --git a/tablib/packages/dbfpy/utils.py b/tablib/packages/dbfpy/utils.py new file mode 100644 index 0000000..cef8aa5 --- /dev/null +++ b/tablib/packages/dbfpy/utils.py @@ -0,0 +1,170 @@ +"""String utilities. + +TODO: + - allow strings in getDateTime routine; +""" +"""History (most recent first): +11-feb-2007 [als] added INVALID_VALUE +10-feb-2007 [als] allow date strings padded with spaces instead of zeroes +20-dec-2005 [yc] handle long objects in getDate/getDateTime +16-dec-2005 [yc] created from ``strutil`` module. +""" + +__version__ = "$Revision: 1.4 $"[11:-2] +__date__ = "$Date: 2007/02/11 08:57:17 $"[7:-2] + +import datetime +import time + + +def unzfill(str): + """Return a string without ASCII NULs. + + This function searchers for the first NUL (ASCII 0) occurance + and truncates string till that position. + + """ + try: + return str[:str.index('\0')] + except ValueError: + return str + + +def getDate(date=None): + """Return `datetime.date` instance. + + Type of the ``date`` argument could be one of the following: + None: + use current date value; + datetime.date: + this value will be returned; + datetime.datetime: + the result of the date.date() will be returned; + string: + assuming "%Y%m%d" or "%y%m%dd" format; + number: + assuming it's a timestamp (returned for example + by the time.time() call; + sequence: + assuming (year, month, day, ...) sequence; + + Additionaly, if ``date`` has callable ``ticks`` attribute, + it will be used and result of the called would be treated + as a timestamp value. + + """ + if date is None: + # use current value + return datetime.date.today() + if isinstance(date, datetime.date): + return date + if isinstance(date, datetime.datetime): + return date.date() + if isinstance(date, (int, long, float)): + # date is a timestamp + return datetime.date.fromtimestamp(date) + if isinstance(date, basestring): + date = date.replace(" ", "0") + if len(date) == 6: + # yymmdd + return datetime.date(*time.strptime(date, "%y%m%d")[:3]) + # yyyymmdd + return datetime.date(*time.strptime(date, "%Y%m%d")[:3]) + if hasattr(date, "__getitem__"): + # a sequence (assuming date/time tuple) + return datetime.date(*date[:3]) + return datetime.date.fromtimestamp(date.ticks()) + + +def getDateTime(value=None): + """Return `datetime.datetime` instance. + + Type of the ``value`` argument could be one of the following: + None: + use current date value; + datetime.date: + result will be converted to the `datetime.datetime` instance + using midnight; + datetime.datetime: + ``value`` will be returned as is; + string: + *** CURRENTLY NOT SUPPORTED ***; + number: + assuming it's a timestamp (returned for example + by the time.time() call; + sequence: + assuming (year, month, day, ...) sequence; + + Additionaly, if ``value`` has callable ``ticks`` attribute, + it will be used and result of the called would be treated + as a timestamp value. + + """ + if value is None: + # use current value + return datetime.datetime.today() + if isinstance(value, datetime.datetime): + return value + if isinstance(value, datetime.date): + return datetime.datetime.fromordinal(value.toordinal()) + if isinstance(value, (int, long, float)): + # value is a timestamp + return datetime.datetime.fromtimestamp(value) + if isinstance(value, basestring): + raise NotImplementedError("Strings aren't currently implemented") + if hasattr(value, "__getitem__"): + # a sequence (assuming date/time tuple) + return datetime.datetime(*tuple(value)[:6]) + return datetime.datetime.fromtimestamp(value.ticks()) + + +class classproperty(property): + """Works in the same way as a ``property``, but for the classes.""" + + def __get__(self, obj, cls): + return self.fget(cls) + + +class _InvalidValue(object): + + """Value returned from DBF records when field validation fails + + The value is not equal to anything except for itself + and equal to all empty values: None, 0, empty string etc. + In other words, invalid value is equal to None and not equal + to None at the same time. + + This value yields zero upon explicit conversion to a number type, + empty string for string types, and False for boolean. + + """ + + def __eq__(self, other): + return not other + + def __ne__(self, other): + return not (other is self) + + def __nonzero__(self): + return False + + def __int__(self): + return 0 + __long__ = __int__ + + def __float__(self): + return 0.0 + + def __str__(self): + return "" + + def __unicode__(self): + return u"" + + def __repr__(self): + return "<INVALID>" + +# invalid value is a constant singleton +INVALID_VALUE = _InvalidValue() + +# vim: set et sts=4 sw=4 : |
