mirror of
https://github.com/kennethreitz/tablib.git
synced 2026-06-05 15:00:19 +00:00
a21f8187f8
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 🍰 @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 🍰 @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.
263 lines
8.2 KiB
Python
263 lines
8.2 KiB
Python
"""DBF record definition.
|
|
|
|
"""
|
|
"""History (most recent first):
|
|
11-feb-2007 [als] __repr__: added special case for invalid field values
|
|
10-feb-2007 [als] added .rawFromStream()
|
|
30-oct-2006 [als] fix record length in .fromStream()
|
|
04-jul-2006 [als] added export declaration
|
|
20-dec-2005 [yc] DbfRecord.write() -> DbfRecord._write();
|
|
added delete() method.
|
|
16-dec-2005 [yc] record definition moved from `dbf`.
|
|
"""
|
|
|
|
__version__ = "$Revision: 1.7 $"[11:-2]
|
|
__date__ = "$Date: 2007/02/11 09:05:49 $"[7:-2]
|
|
|
|
__all__ = ["DbfRecord"]
|
|
|
|
from itertools import izip
|
|
|
|
import utils
|
|
|
|
class DbfRecord(object):
|
|
"""DBF record.
|
|
|
|
Instances of this class shouldn't be created manualy,
|
|
use `dbf.Dbf.newRecord` instead.
|
|
|
|
Class implements mapping/sequence interface, so
|
|
fields could be accessed via their names or indexes
|
|
(names is a preffered way to access fields).
|
|
|
|
Hint:
|
|
Use `store` method to save modified record.
|
|
|
|
Examples:
|
|
Add new record to the database:
|
|
db = Dbf(filename)
|
|
rec = db.newRecord()
|
|
rec["FIELD1"] = value1
|
|
rec["FIELD2"] = value2
|
|
rec.store()
|
|
Or the same, but modify existed
|
|
(second in this case) record:
|
|
db = Dbf(filename)
|
|
rec = db[2]
|
|
rec["FIELD1"] = value1
|
|
rec["FIELD2"] = value2
|
|
rec.store()
|
|
|
|
"""
|
|
|
|
__slots__ = "dbf", "index", "deleted", "fieldData"
|
|
|
|
## creation and initialization
|
|
|
|
def __init__(self, dbf, index=None, deleted=False, data=None):
|
|
"""Instance initialiation.
|
|
|
|
Arguments:
|
|
dbf:
|
|
A `Dbf.Dbf` instance this record belonogs to.
|
|
index:
|
|
An integer record index or None. If this value is
|
|
None, record will be appended to the DBF.
|
|
deleted:
|
|
Boolean flag indicating whether this record
|
|
is a deleted record.
|
|
data:
|
|
A sequence or None. This is a data of the fields.
|
|
If this argument is None, default values will be used.
|
|
|
|
"""
|
|
self.dbf = dbf
|
|
# XXX: I'm not sure ``index`` is necessary
|
|
self.index = index
|
|
self.deleted = deleted
|
|
if data is None:
|
|
self.fieldData = [_fd.defaultValue for _fd in dbf.header.fields]
|
|
else:
|
|
self.fieldData = list(data)
|
|
|
|
# XXX: validate self.index before calculating position?
|
|
position = property(lambda self: self.dbf.header.headerLength + \
|
|
self.index * self.dbf.header.recordLength)
|
|
|
|
def rawFromStream(cls, dbf, index):
|
|
"""Return raw record contents read from the stream.
|
|
|
|
Arguments:
|
|
dbf:
|
|
A `Dbf.Dbf` instance containing the record.
|
|
index:
|
|
Index of the record in the records' container.
|
|
This argument can't be None in this call.
|
|
|
|
Return value is a string containing record data in DBF format.
|
|
|
|
"""
|
|
# XXX: may be write smth assuming, that current stream
|
|
# position is the required one? it could save some
|
|
# time required to calculate where to seek in the file
|
|
dbf.stream.seek(dbf.header.headerLength +
|
|
index * dbf.header.recordLength)
|
|
return dbf.stream.read(dbf.header.recordLength)
|
|
rawFromStream = classmethod(rawFromStream)
|
|
|
|
def fromStream(cls, dbf, index):
|
|
"""Return a record read from the stream.
|
|
|
|
Arguments:
|
|
dbf:
|
|
A `Dbf.Dbf` instance new record should belong to.
|
|
index:
|
|
Index of the record in the records' container.
|
|
This argument can't be None in this call.
|
|
|
|
Return value is an instance of the current class.
|
|
|
|
"""
|
|
return cls.fromString(dbf, cls.rawFromStream(dbf, index), index)
|
|
fromStream = classmethod(fromStream)
|
|
|
|
def fromString(cls, dbf, string, index=None):
|
|
"""Return record read from the string object.
|
|
|
|
Arguments:
|
|
dbf:
|
|
A `Dbf.Dbf` instance new record should belong to.
|
|
string:
|
|
A string new record should be created from.
|
|
index:
|
|
Index of the record in the container. If this
|
|
argument is None, record will be appended.
|
|
|
|
Return value is an instance of the current class.
|
|
|
|
"""
|
|
return cls(dbf, index, string[0]=="*",
|
|
[_fd.decodeFromRecord(string) for _fd in dbf.header.fields])
|
|
fromString = classmethod(fromString)
|
|
|
|
## object representation
|
|
|
|
def __repr__(self):
|
|
_template = "%%%ds: %%s (%%s)" % max([len(_fld)
|
|
for _fld in self.dbf.fieldNames])
|
|
_rv = []
|
|
for _fld in self.dbf.fieldNames:
|
|
_val = self[_fld]
|
|
if _val is utils.INVALID_VALUE:
|
|
_rv.append(_template %
|
|
(_fld, "None", "value cannot be decoded"))
|
|
else:
|
|
_rv.append(_template % (_fld, _val, type(_val)))
|
|
return "\n".join(_rv)
|
|
|
|
## protected methods
|
|
|
|
def _write(self):
|
|
"""Write data to the dbf stream.
|
|
|
|
Note:
|
|
This isn't a public method, it's better to
|
|
use 'store' instead publically.
|
|
Be design ``_write`` method should be called
|
|
only from the `Dbf` instance.
|
|
|
|
|
|
"""
|
|
self._validateIndex(False)
|
|
self.dbf.stream.seek(self.position)
|
|
self.dbf.stream.write(self.toString())
|
|
# FIXME: may be move this write somewhere else?
|
|
# why we should check this condition for each record?
|
|
if self.index == len(self.dbf):
|
|
# this is the last record,
|
|
# we should write SUB (ASCII 26)
|
|
self.dbf.stream.write("\x1A")
|
|
|
|
## utility methods
|
|
|
|
def _validateIndex(self, allowUndefined=True, checkRange=False):
|
|
"""Valid ``self.index`` value.
|
|
|
|
If ``allowUndefined`` argument is True functions does nothing
|
|
in case of ``self.index`` pointing to None object.
|
|
|
|
"""
|
|
if self.index is None:
|
|
if not allowUndefined:
|
|
raise ValueError("Index is undefined")
|
|
elif self.index < 0:
|
|
raise ValueError("Index can't be negative (%s)" % self.index)
|
|
elif checkRange and self.index <= self.dbf.header.recordCount:
|
|
raise ValueError("There are only %d records in the DBF" %
|
|
self.dbf.header.recordCount)
|
|
|
|
## interface methods
|
|
|
|
def store(self):
|
|
"""Store current record in the DBF.
|
|
|
|
If ``self.index`` is None, this record will be appended to the
|
|
records of the DBF this records belongs to; or replaced otherwise.
|
|
|
|
"""
|
|
self._validateIndex()
|
|
if self.index is None:
|
|
self.index = len(self.dbf)
|
|
self.dbf.append(self)
|
|
else:
|
|
self.dbf[self.index] = self
|
|
|
|
def delete(self):
|
|
"""Mark method as deleted."""
|
|
self.deleted = True
|
|
|
|
def toString(self):
|
|
"""Return string packed record values."""
|
|
return "".join([" *"[self.deleted]] + [
|
|
_def.encodeValue(_dat)
|
|
for (_def, _dat) in izip(self.dbf.header.fields, self.fieldData)
|
|
])
|
|
|
|
def asList(self):
|
|
"""Return a flat list of fields.
|
|
|
|
Note:
|
|
Change of the list's values won't change
|
|
real values stored in this object.
|
|
|
|
"""
|
|
return self.fieldData[:]
|
|
|
|
def asDict(self):
|
|
"""Return a dictionary of fields.
|
|
|
|
Note:
|
|
Change of the dicts's values won't change
|
|
real values stored in this object.
|
|
|
|
"""
|
|
return dict([_i for _i in izip(self.dbf.fieldNames, self.fieldData)])
|
|
|
|
def __getitem__(self, key):
|
|
"""Return value by field name or field index."""
|
|
if isinstance(key, (long, int)):
|
|
# integer index of the field
|
|
return self.fieldData[key]
|
|
# assuming string field name
|
|
return self.fieldData[self.dbf.indexOfFieldName(key)]
|
|
|
|
def __setitem__(self, key, value):
|
|
"""Set field value by integer index of the field or string name."""
|
|
if isinstance(key, (int, long)):
|
|
# integer index of the field
|
|
return self.fieldData[key]
|
|
# assuming string field name
|
|
self.fieldData[self.dbf.indexOfFieldName(key)] = value
|
|
|
|
# vim: et sts=4 sw=4 :
|