Ejemplo n.º 1
0
 def parse(cls_,
           file_handle,
           date_format=None,
           months_first=None,
           thousands_separator=None,
           currency_num_fractional_digits=None):
     if months_first is not None:
         cls_._months_first = months_first
     if thousands_separator is not None:
         cls_._thousands_separator = thousands_separator
     if currency_num_fractional_digits is not None:
         Qif.set_currency_num_fractional_digits(
             int(currency_num_fractional_digits))
     if isinstance(file_handle, type('')):
         raise RuntimeError(
             six.u("parse() takes in a file handle, not a string"))
     data = file_handle.read()
     if len(data) == 0:
         raise QifParserException('Data is empty')
     qif_obj = Qif()
     chunks = data.split('\n^\n')
     last_type = None
     last_account = None
     transactions_header = None
     parsers = {
         'category': cls_.parseCategory,
         'account': cls_.parseAccount,
         'transaction': cls_.parseTransaction,
         'investment': cls_.parseInvestment,
         'class': cls_.parseClass,
         'memorized': cls_.parseMemorizedTransaction
     }
     for chunk in chunks:
         if not chunk:
             continue
         first_line = chunk.split('\n')[0]
         first_line = first_line.strip()
         if first_line == '!Type:Cat':
             last_type = 'category'
         elif first_line == '!Account':
             last_type = 'account'
         elif first_line in NON_INVST_ACCOUNT_TYPES:
             last_type = 'transaction'
             transactions_header = first_line
         elif first_line == '!Type:Invst':
             last_type = 'investment'
             transactions_header = first_line
         elif first_line == '!Type:Class':
             last_type = 'class'
         elif first_line == '!Type:Memorized':
             last_type = 'memorized'
             transactions_header = first_line
         elif chunk.startswith('!'):
             raise QifParserException('Header not reconized')
         # if no header is recognized then
         # we use the previous one
         item = parsers[last_type](chunk)
         if last_type == 'account':
             qif_obj.add_account(item)
             last_account = item
         elif last_type == 'transaction'\
                 or last_type == 'memorized' or last_type == 'investment':
             if last_account:
                 last_account.add_transaction(item,
                                              header=transactions_header)
             else:
                 qif_obj.add_transaction(item, header=transactions_header)
         elif last_type == 'category':
             qif_obj.add_category(item)
         elif last_type == 'class':
             qif_obj.add_class(item)
     return qif_obj