A better MT940 has become available on PyPI

This commit is contained in:
Raphael Michel
2015-10-18 18:05:47 +02:00
parent ae4d102288
commit 705d8bd931
5 changed files with 22 additions and 318 deletions

View File

@@ -1,54 +1,26 @@
import io
from collections import defaultdict
from decimal import Decimal
from . import mt940
class MT940(mt940.MT940):
def __init__(self, f):
# Default implementation only takes a filename, but our file object
# is not necessarily a file on the disk.
self.statements = []
values = defaultdict(str)
transactions = []
for line in self._readline(f):
for name, sections in mt940.SECTIONS.items():
if name == 'begin':
continue
for section in sections:
if line.startswith(section):
if name in values and name == 'statement':
self._set_statement(values, transactions)
if name.endswith('_balance'):
values[name] = self._get_balance(
line[len(section):])
elif name == 'transaction':
transactions.append(
self._get_transaction(line[len(section):]))
elif name == 'description':
transactions[-1] = (transactions[-1][:-1]
+ (line[len(section):],))
else:
values[name] += line[len(section):]
if values:
self._set_statement(values, transactions)
import mt940
def parse(file):
data = file.read()
try:
import chardet
charset = chardet.detect(data)['encoding']
except ImportError:
charset = file.charset
data = data.decode(charset or 'utf-8')
mt = MT940(io.StringIO(data))
mt = mt940.parse(io.StringIO(data.strip()))
result = []
for statement in mt.statements:
for t in statement.transactions:
result.append({
'reference': t.reference + '\n' + t.description,
'amount': str(t.amount),
'date': t.booking.isoformat(),
})
for t in mt:
result.append({
'reference': "\n".join([
t.data.get(f) for f in ('transaction_details', 'customer_reference', 'bank_reference',
'extra_details') if t.data.get(f, '')]),
'amount': str(t.data['amount'].amount.quantize(Decimal('.01'))),
'date': t.data['date'].isoformat()
})
return result