Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update __init__.py #3

Merged
merged 2 commits into from
Dec 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions localdb/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# © Amit Sharma <https://github.com/buddhhu>

import json
from os.path import getsize

__version__ = "1.0"
Expand All @@ -20,14 +21,21 @@ def _raw_data(self):
"""Returns raw data from database file"""
try:
with open(self.name, "r") as data:
return data.read()
try:
return json.load(data)
except Exception as er:
return data.read()
except FileNotFoundError:
self._create_database(self.name)
return self._raw_data()

def _data(self):
"""Converts raw data into dict"""
self._cache = eval(self._raw_data())
data = self._raw_data()
if isinstance(data, str):
self._cache = eval(self._raw_data())
else:
self._cache = data

def get(self, key):
"""Get the requested key, uses cache before reading database file."""
Expand All @@ -45,7 +53,7 @@ def set(self, key=None, value=None, delete_key=None):
if key and value:
data.update({key: value})
with open(self.name, "w") as dbfile:
dbfile.write(str(data))
json.dump(data, dbfile)
self._data()
return True

Expand Down