Skip to content

Commit

Permalink
some code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Fl1yd committed May 15, 2022
1 parent a6dfea7 commit 9f83ef7
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 68 deletions.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2021 Fl1yd
Copyright (c) 2021-2022 Fl1yd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
40 changes: 23 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,40 +1,46 @@
LightDB
=======
<h1>LightDB</h1>


What is this?
-------------
<h2>What is this?</h2>

LightDB is a lightweight JSON Database for Python
that allows you to **quickly** and **easily** write data to a file
that allows you to <b>quickly</b> and <b>easily</b> write data to a file


Installing
----------
```Shell
<h2>Installing</h2>

<pre lang="bash">
pip3 install lightdb
```
</pre>


<h2>How to use</h2>

How to use
----------
```Python
<pre lang="python">
from lightdb import LightDB

db = LightDB("/path/to/file.json") # or a non-existent file, it will be created automatically

# `SET` method:
# SET method:

data = {
"key1": "value1",
"key2": ["value2", "value3", ...],
"key2": [
"value2",
"value3",
...
],
...
}
db.set("key3", data)
data = ["value4", "value5"]
db.set("key4", data)


# or `GET`:
# or GET:

print(db.get("key3"))
# {"key1": "value1", "key2": ["value2", "value3", ...]}
# {"key1": "value1", "key2": ["value2", "value3"]}
print(db.get("key4"))
# ["value4", "value5"]
```
</pre>
142 changes: 96 additions & 46 deletions lightdb/LightDB.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,30 @@
"""The main file for the LightDB project.
:copyright: (c) 2021-2022 by Fl1yd.
:license: MIT, see LICENSE for more details.
"""

import os
import json

from typing import Union, Dict


class LightDB(dict):
"""
Light Database
"""Light DataBase
~~~~~~~~~~~~~~
`SET` method usage:
>>> from lightdb import LightDB
>>> db = LightDB("/path/to/file.json") # or a non-existent file, it will be created automatically
>>> db = LightDB("/path/to/file.json") # or a non-existent file, it will be created automatically
>>> data = {
"key1": "value1",
"key2": ["value2", "value3", ...],
"key2": [
"value2",
"value3",
...
],
...
}
>>> db.set("key3", data)
Expand All @@ -25,89 +36,128 @@ class LightDB(dict):
... or `GET`:
>>> db.get("key3")
{"key1": "value1", "key2": ["value2", "value3", ...]}
{"key1": "value1", "key2": ["value2", "value3"]}
>>> db.get("key4")
["value4", "value5"]
"""

def __init__(self, location: str):
def __init__(self, location: str) -> None:
"""Initialize the LightDB object
Params:
location (``str``):
The location of the database file
Returns:
None
"""
super().__init__()
self.location = location
self.update(**self.load())
self.update(**self._load())

def __repr__(self):
def __repr__(self) -> str:
return object.__repr__(self)

def load(self):
def _load(self) -> Dict[str, Union[str, int, float, list, dict]]:
"""Load the data from a file
Returns:
The data from the file
"""
return (
json.load(open(self.location, "r"))
if os.path.exists(self.location)
else {}
)

def save(self):
def save(self) -> bool:
"""Save the current data to a file
Returns:
bool
"""
json.dump(
self, open(self.location, "w+"),
ensure_ascii = False, indent = 4
ensure_ascii=False, indent=4
)
return True

def set(self, key, value):
"""
LightDB `SET` method
def set(
self, key: str, value: Union[str, int, float, list, dict]
) -> bool:
"""LightDB `SET` method
Params:
key (``str``):
The keyname of the item you want to set
value (``str`` | ``int`` | ``float`` | ``list`` | ``dict``):
The value of the item you want to set
Returns:
bool
Usage:
>>> data = {
"key1": "value1",
"key2": ["value2", "value3"]
}
"key1": "value1",
"key2": [
"value2",
"value3"
]
}
>>> db.set("key3", data)
True
:params: The keyname and value you want to set
:return: True
"""

self[key] = value
self[str(key)] = value
return self.save()

def get(self, key, default = None):
"""
LightDB `GET` method
def get(
self, key: str, default: Union[str, int, float, list, dict] = None
) -> Dict[str, Union[str, int, float, list, dict]]:
"""LightDB `GET` method
Params:
key (``str``):
The keyname of the item you want to get
default (``str`` | ``int`` | ``float`` | ``list`` | ``dict``, optional):
The default value if the key doesn't exist
Returns:
The value of the item with the specified key
Usage:
>>> db.get("key3")
>>> result = db.get("key3")
>>> result
{"key1": "value1", "key2": ["value2", "value3"]}
>>> r = db.get("key3")
>>> r["key2"].remove("value3")
>>> r
>>> result["key2"].remove("value3")
>>> result
{"key1": "value1", "key2": ["value2"]}
:params:
key - The keyname of the item you want to return the value from
default - A value to return if the specified key does not exist. Default value `None`
:return: The value of the item with the specified key
"""
return dict(self).get(str(key), default)

return dict(self).get(key, default)
def pop(
self, key: str
) -> Dict[str, Union[str, int, float, list, dict]]:
"""LightDB `POP` method
def pop(self, key):
"""
LightDB `POP` method
Params:
key (``str``):
The keyname of the item you want to pop
Returns:
The value of the item with the specified key
Usage:
>>> db.pop("key1")
{"key1": "value1", "key2": ["value2", "value3"]}
:params: The keyname of the item you want to remove
:return: The value of the removed item
"""

popped = self.get(key)
del self[key]
popped = self[str(key)]
del self[str(key)]
self.save()
return popped

def reset(self):
def reset(self) -> bool:
"""Reset database data"""
self.clear()
return self.save()
return self.save()
7 changes: 3 additions & 4 deletions lightdb/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
"""
See LightDB docstring:
"""See LightDB docstring:
from LightDB import LightDB
---------------------
:copyright: (c) 2021 by Fl1yd.
:copyright: (c) 2021-2022 by Fl1yd.
:license: MIT, see LICENSE for more details.
"""

from .LightDB import LightDB

__version__ = "1.1"
__version__ = "1.2"

0 comments on commit 9f83ef7

Please sign in to comment.