Closed roniemartinez closed 7 years ago
Hey! I think the case that a database file is not writable isn't very common. I think the best solution here would be to create a copy of the JSONStorage and adapt it by removing the write functionality (maybe by throwing an exception). More details on custom storages can be found in the docs. What do you think?
Maybe writing a Read-Only JSONStorage is a better idea [for now].
I am also thinking of monkey-patching the touch() function. This is possible, right?
Cheers!
I am also thinking of monkey-patching the touch() function. This is possible, right?
I think if you take the JSONStorage as it currently is and remove all the stuff that is used to write new entries, you won't need to monkey-patch the touch() function. You could go with something like this:
class JSONStorageReadOnly(Storage):
"""
Store the data in a JSON file.
"""
def __init__(self, path):
"""
Create a new instance.
:param path: Where to store the JSON data.
:type path: str
"""
super(JSONStorage, self).__init__()
self._handle = open(path, 'r')
def close(self):
self._handle.close()
def read(self):
return json.load(self._handle)
def write(self, data):
raise RuntimeError('JSONStorageReadOnly cannot write data')
Thanks a lot @msiemens :+1:
in JSONStorage you open a file and then in the readonly you open it again. That's file description leak. Perhaps a Middleware would be more appropriate?
Edit: or is it actually skipping the JSONStora.init ...?
@rafalkrupinski You're right actually! Using a middleware would be more correct in this case.
If you came to this page looking for the "read-only" option (like I did) -- here you are: there is an access_mode
option now. You can open your database like this: db = TinyDB("db.json", access_mode='r')
and it will be read-only. Thanks for adding this option, @jmborr !
Hi,
I recently used TinyDB and added it (including the pre-processed JSON data file) to my PyPI package. Everything works fine but not on systems with lower permissions - READ-ONLY.
As you can see, 'a' mode on open() function is hardcoded. The use case is only to read the file, though.
For now the quick fix is to add write permission to the required JSON file. If there is an option to modify the mode, that will be great!
Thanks.