def match(self, file_in): with open(file_in, 'rb') as csv_file: try: result = parse_csv(csv_file, self.get_fieldnames(), dayfirst=self.date_day_first, skip_rows=self.data_start_row, max_rows=2) #TODO: we could assert 2 transactions were found, but that # would mean that you'd always need two transactions in every # file you want to import except: return False else: return True
def import_csv(filename, account): ''' ''' # CSVs come in many formats, find a matching profile for profile in CsvImportProfile.objects.all().order_by('order'): if profile.match(filename): logging.info("Found matching CSV profile: %s", profile) break else: raise ValueError, "No profiles matched the file" with open(filename, 'rb') as csv_file: transactions = parse_csv(csv_file, profile.get_fieldnames(), dayfirst=profile.date_day_first, skip_rows=profile.data_start_row) logging.info("%d CSV transactions found in file %s", len(transactions), filename) for t in transactions: # split payee string into parts try: trans_type, payee = match_transaction_type(t['payee']) except ValueError: logging.warning("Transaction type cannot be determined: %s", t['payee']) trans_type = None payee = t['payee'] # create and save Transactions in DB new_transaction = Transaction( account = account, name = payee, #TODO: populate or remove as we don't need a name?! date = t['date'], transaction_type = trans_type, payee = payee, ##paid_on = paid_on_dt, ##import_string = t['import_string'], # DictReader doesn't give us the original line ) new_transaction.save() t_part = TransactionPart( transaction = new_transaction, amount = '%.2f' % t['amount'], category = match_category(payee), ) t_part.save() logging.debug("Imported %s - %s", new_transaction, t_part) return len(transactions)
def test_parse_csv_sample(self): ts = parse_csv(SAMPLE_CSV) assert len(ts) == 10