JSON Database in Python

Greetings!

I want to tell you about my development – JSON DB in Python

Not all projects need slow and complex SQL databases, for example TG-Bots and parsers. Of course, I will not argue that SQL is probably the best solution for business, but sometimes they can be redundant for small projects. NoSQL databases are a great choice for such cases.

If you are already familiar with MongoDB or Redis, then the principle of my library will be clear to you.

Let `s start?

Basics

from jsoner import Database

# инициализация объекта БД
db = Database('db.json')

 # добавление данных
db.add('key', 'value')

# получение
db.get('key') # 'value'

# запись изменений в файл
db.commit()

# изменение значения
db.update('key', 100)

# увеличение значения на 5
db.incr(key, 5)

# уменьшение значения на 15
db.decr(key, 15)

# удаление
db.delete('key')

Tags

Tags are created by adding a dictionary of Tag: value pairs

from jsoner import Database
from jsoner.tags import const_tag
from jsoner.errors import ValueIsConstant

db = Database('db.json', autocommit=True)

# тег неизменяемого значения
db.add('pi', 3.14, {const_tag: True})

try:
    db.update('pi', 4)
except ValueIsConstant:
     print('Ключ "pi" - константа')

>>> 'Ключ "pi" - константа'

Tags and their values ​​are written to a dictionary tags

db.json

{
    "__settings__": {
        "__version__": "0.1", 
        "default": null,
        "tags": {
            "pi": {
                "const": true
            }
        }, 
        "global_tags": {}
    },
    "pi": 3.14
}

Create your own tags

With the help of class NewTag you can create your own tags

from jsoner import Database
from jsoner.tags import NewTag

db = Database('db.json')

class MyTag(NewTag):

    # создании тега, метод должен вернуть преобразованный аргумент тега
    def create(db: Database, value, tag_arg):
        return tag_arg

    # изменение значения
    def update(db: Database, key: str, old_value, new_value, tag_arg):
        return new_value

    # чтение значения
    def read(db: Database, key: str, value, tag_arg):
        return value

Example of creating your own tag

from jsoner import Database
from jsoner.tags import NewTag
import time

class ttl_tag(NewTag):
    'Time to life - время жизни ключа'

    def create(db: Database, value, tag_arg) -> str:

        # tag_arg в данном случае - время действия ключа
        # в аргументе тега сохранится время, до которого действителен ключ
        
        return tag_arg + time.time()

    def read(db: Database, key, value, tag_arg):

        # если текущее время больше аргумента тега, ключ следует удалить, и вернуть значение по умолчанию
        
        if time.time() <= tag_arg:
            return value
        else:
            db.delete(key)
            return db.data[db.settings]['default'] # тут хранится значение по умолчанию

Setting the default value

from jsoner import Database

db = Database('data.json')

# установка значения по умолчанию
db.set_default(0)

print(db.get('Unknown key'))
>>> 0

Adding Global Tags

Global tags are valid and the same for all keys

from jsoner import Database
from jsoner.tags import const_tag
from jsoner.errors import ValueIsConstant

db = Database('data.json')

# добавление глобального тега
db.set_global_tag(const_tag, True)

db.add('num', 123)
db.update('num', 0)
>>> raise ValueIsConstant

Working with the with operator

When entering the operator with the method is called db.discard()which erases unsaved data in a file

If attribute autocommit at db equal Truethen it will be replaced by Falseand when exiting with will come back

When exiting with the method is called db.commit()

from jsoner import Database

db = Database('data.json')

db.add('num', 0)

with db:
    db.add('key', 'value')

print(db.items())
>>> [('key', 'value')]

Other useful methods

  • discard – erase unsaved data in the file

  • get_many – get multiple values ​​by keys

  • set – automatically either adds or modifies data. Because adding an existing key or updating a non-existent one will cause an exception

  • keys, values, items – similar to methods from regular dictionaries

  • db['key'] = 'value' – set value

  • db['key'] – read the meaning

You can see the full description and code on my github

Afterword

I will accept constructive criticism, but uncles-programmers, I want to tell you that I am 15 years old, so do not judge strictly

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *