msiemens / tinydb

TinyDB is a lightweight document oriented database optimized for your happiness :)
https://tinydb.readthedocs.org
MIT License
6.76k stars 534 forks source link

how to flush Tables with CachingMiddleware(JSONStorage)) #519

Closed joytsay closed 1 year ago

joytsay commented 1 year ago

As the README said https://github.com/msiemens/tinydb#using-middlewares , you can

from tinydb.storages import JSONStorage
from tinydb.middlewares import CachingMiddleware
db = TinyDB('/path/to/db.json', storage=CachingMiddleware(JSONStorage))
db.storage.flush() # force save

Originally posted by @liukun in https://github.com/msiemens/tinydb/issues/397#issuecomment-862094356

Hi @msiemens As the suggestion above, one can speed read/write via CachingMiddleware, But when using it with Tables, I encounter this error when saving (flush):

db.flush() # force save
  File "C:\Users\joytsay.DDTL-RD-JOYTSAY\miniconda3\envs\torchface\lib\site-packages\tinydb\database.py", line 255, in __getattr__
    return getattr(self.table(self.default_table_name), name)
AttributeError: 'Table' object has no attribute 'flush'

In my code I just imported Tables and use db flush:

from tinydb import TinyDB
from tinydb.middlewares import CachingMiddleware
from tinydb.storages import JSONStorage
from tinydb.table import Table

db = TinyDB("./database.json", storage=CachingMiddleware(JSONStorage))
db.flush() # force save

does CachingMiddleware(JSONStorage)) just not work with Tables? or am i using it wrong (sorry i'm a newb when it comes to SQL and databases)

joytsay commented 1 year ago

sorry i found its's db.storage.flush() instead of my typo db.flush() my bad, closing issue ; )

msiemens commented 1 year ago

You're correct 🙂 I'm glad you found the answer!