How to use the piecash.open_book function in piecash

To help you get started, we’ve selected a few piecash examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sdementen / piecash / tests / test_book.py View on Github external
def test_open_RW_backup(self, book_uri):
        # create book
        with create_book(uri_conn=book_uri) as b:
            engine_type = b.session.bind.name

        # open book with readonly = False (ie RW)
        if engine_type != "sqlite":
            # raise an exception as try to do a backup on postgres which is not supported yet
            with pytest.raises(GnucashException):
                b = open_book(uri_conn=book_uri, readonly=False)

        elif engine_type == "sqlite":
            # delete all potential existing backup files
            url = book_uri[len("sqlite:///"):]
            for fn in glob.glob("{}.[0-9]*.gnucash".format(url)):
                os.remove(fn)

            # open file in RW without a backup creation
            with open_book(uri_conn=book_uri, readonly=False, do_backup=False) as b:
                pass

            # check no backup file creation
            assert len(glob.glob("{}.[0-9]*.gnucash".format(url))) == 0

            # open file in RW without a backup creation
            with open_book(uri_conn=book_uri, readonly=False) as b:
github sdementen / piecash / tests / test_integration.py View on Github external
def use_copied_book(request, template_filename, test_filename, check_same_thread=True):
    shutil.copy(str(template_filename), str(test_filename))

    # default book is readonly
    s = open_book(test_filename, check_same_thread=check_same_thread)

    @request.addfinalizer
    def finalizer():
        s.close()
        os.remove(test_filename)

    return s
github MisterY / gnucash-portfolio / gnucash_portfolio / lib / database.py View on Github external
if file_url.scheme == "file" or file_url.scheme == "sqlite":
            filename = file_url.path[1:]
        else:
            filename = self.filename

        if not os.path.isfile(filename):
            log(WARN, "Database %s requested but not found. Creating an in-memory book.", filename)
            return self.create_book()

        access_type = "read/write" if for_writing else "readonly"
        log(INFO, "Using %s in %s mode.", filename, access_type)
        # file_path = path.relpath(self.filename)
        file_path = path.abspath(filename)

        if not for_writing:
            book = piecash.open_book(file_path, open_if_lock=True)
        else:
            book = piecash.open_book(file_path, open_if_lock=True, readonly=False)
        # book = create_book()
        return book
github hiromu2000 / mintcash / mintcash / main.py View on Github external
def add_categories(self):
        book = piecash.open_book(uri_conn=self.dbname, readonly=False, do_backup=False)
        USD = book.commodities.get(mnemonic='USD')
        types = self.types

        # Create level=2 Gnucash accounts for Mint depth=1 categories
        categories = {}
        for category in self.mint.get_categories().itervalues():
            categories[category['id']] = category
            parent = category['parent']
            categories[parent['id']] = parent

        for category in categories.itervalues():
            if category['depth'] == 1:
                acc = piecash.Account(name=category['name'],
                                type=types[category['categoryType']]['gnucash_type'],
                                parent=book.accounts(name=types[category['categoryType']]['name']),
                                code=str(category['id']),
github sdementen / piecash / examples / sandbox.py View on Github external
if any(tr.calculate_imbalances()[1]):
            print(before)
            tr.normalize_trading_accounts()
            print(tr.ledger_str())

    s.save()
fdsfdsfds

with create_book("test_bitcoin.gnucash", overwrite=True) as s:
    root = s.book.root_account
    bitcoin = Commodity("CURRENCY", "XBT", "Bitcoin", 1000000)
    Account("My bitcoin account", "BANK", bitcoin, parent=root)
    s.save()
fdsfds

with open_book("../gnucash_books/default_book.gnucash") as s:
    # accessing the book object from the session
    book = s.book

    # accessing root accounts
    root = book.root_account

    # accessing children accounts of root
    r = s.book.root_account.children(name="Assets").children[0]
    for acc in s.book.root_account.children(name="Assets").children[0].children:
        print(acc)

    print(inspect.getmro(Budget))
    print(inspect.getmro(Recurrence))
    b = Budget(name=lambda x: x, foo="3")
    b = Budget(name=lambda x: x, foo="3")
    fdsd
github jrwrigh / csv2cash / csv2cash / main.py View on Github external
def import2cash(transactions_compiled, path_to_Book):
    book = piecash.open_book(path_to_Book.as_posix(), readonly=False)

    if len(book.commodities) == 1:
        currency = book.commodities[0]

    try:
        book.accounts(name='Uncategorized')
    except:
        _ = piecash.Account(
            "Uncategorized", "EXPENSE", currency, parent=book.root_account)
        book.save()

    for _, transaction in transactions_compiled.iterrows():
        _ = piecash.Transaction(
            currency=currency,
            description=transaction['description'],
            splits=[
github sdementen / piecash / examples / simple_session.py View on Github external
from __future__ import print_function
import os
import tempfile

from piecash import open_book, create_book, GnucashException


FILE_1 = os.path.join(tempfile.gettempdir(), "not_there.gnucash")
FILE_2 = os.path.join(tempfile.gettempdir(), "example_file.gnucash")

if os.path.exists(FILE_2):
    os.remove(FILE_2)

# open a file that isn't there, detect the error
try:
    book = open_book(FILE_1)
except GnucashException as backend_exception:
    print("OK", backend_exception)

# create a new file, this requires a file type specification
with create_book(FILE_2) as book:
    pass

# open the new file, try to open it a second time, detect the lock
# using the session as context manager automatically release the lock and close the session
with open_book(FILE_2) as book:
    try:
        with open_book(FILE_2) as book_2:
            pass
    except GnucashException as backend_exception:
        print("OK", backend_exception)
github sdementen / piecash / examples / sandbox.py View on Github external
XBT = Commodity(namespace="CURRENCY", mnemonic="XBT", fullname="Bitcoin", fraction=1000000)
print(XBT)
cxwcxwcxw
# with create_book("empty.gnucash", overwrite=True) as s:
# print(list(s.book.iteritems()))

# with open_book("test_bitcoin_piecash.gnucash", readonly=False, open_if_lock=True, backup=False) as s:
# for tr in s.transactions:
# print(tr.ledger_str())
# with create_book("super_empty_piecash.gnucash") as s:
# pass
# dffdsfds


with open_book("super_empty_piecash.gnucash", readonly=False, open_if_lock=True, backup=False) as s:
    print(s.book.root_account.commodity)
    print(s.commodities)
    fdfdsfds
    sa = s.session
    sql = sa.query(Split.value).filter_by(value=100)
    print(sql)
    print(sql.all())
    # print(list(sa.execute("select * from splits")))

dsdsqdsq
#
with open_book("test_bitcoin_piecash.gnucash", readonly=False, open_if_lock=True, backup=False) as s:
    # print(s.book.use_trading_accounts)
    # print(s.book.RO_threshold_day)
    # s.book.use_split_action_field=True
    # print(list(s.book.iteritems()))
github sdementen / piecash / examples / sandbox.py View on Github external
#         # print tr.get_imbalances()
#         for sp in tr.splits:
#             print "\t[{}] {} / {} for {}".format( sp.account.commodity,sp.value, sp.quantity,sp.account)
#     # tr1 = s.transactions.get(description="first")
#     # tr2 = s.transactions[1]
#     tr2 = s.transactions.get(description="cross CAD to USD transfer (initiated from USD account)")
#     sp = s.transactions.get(description="cross CAD to USD transfer").splits[0]
#     # sp = s.transactions[0].splits[0]
#     print "o"*100
#     # print sp
#     print "o"*100
#     sp.transaction = tr2
#     s.session.flush()
# fdfdsfsd

with open_book("trading_accounts.gnucash", readonly=False, open_if_lock=True, acquire_lock=True) as s:
    for tr in s.transactions:  #.get(description="other transfer + expense")
        print("{}\t{}".format(tr.currency, tr.description))
        # print tr.get_imbalances()
        for sp in tr.splits:
            print("\t[{}] {} / {} for {}".format(sp.account.commodity, sp.value, sp.quantity, sp.account))
    # sp.memo = "foo"
    # tr.description = "foo"
    # s.session.flush()

    tr = s.transactions.get(description="cross CAD to USD transfer (initiated from USD account)")
    sp = s.transactions.get(description="cross CAD to USD transfer").splits[0]
    # sp.transaction = tr
    tr.description = "foo"
    # tr.currency = s.commodities[-1]
    # print "foooooooooooooooooooooooooooooooo"
    # print sp.transaction, s.transactions.get(description="cross CAD to USD transfer").splits[1].transaction
github MisterY / gnucash-portfolio / gnucash_portfolio / actions / search_for_account.py View on Github external
found = False

    # search
    for account in book.accounts:
        # print(account.fullname)
        # name
        if searchTerm.lower() in account.fullname.lower():
            print(account.fullname)
            found = True

    if not found:
        print("Search term not found in account names.")


with piecash.open_book(filename, open_if_lock=True) as book:
    searchAccount(searchTerm, book)