From 6ca086a89a86ab9b01ad8e1ec4621996b08f06e0 Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Sun, 11 Jun 2017 17:44:11 +0300 Subject: [PATCH] docs/btree: Add hints about opening db file and need to flush db. --- docs/library/btree.rst | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/library/btree.rst b/docs/library/btree.rst index bd7890586a..7108fba430 100644 --- a/docs/library/btree.rst +++ b/docs/library/btree.rst @@ -23,7 +23,13 @@ Example:: # First, we need to open a stream which holds a database # This is usually a file, but can be in-memory database # using uio.BytesIO, a raw flash section, etc. - f = open("mydb", "w+b") + # Oftentimes, you want to create a database file if it doesn't + # exist and open if it exists. Idiom below takes care of this. + # DO NOT open database with "a+b" access mode. + try: + f = open("mydb", "r+b") + except OSError: + f = open("mydb", "w+b") # Now open a database itself db = btree.open(f) @@ -33,6 +39,11 @@ Example:: db[b"1"] = b"one" db[b"2"] = b"two" + # Assume that any changes are cached in memory unless + # explicitly flushed (or database closed). Flush database + # at the end of each "transaction". + db.flush() + # Prints b'two' print(db[b"2"])