August 3, 2023

Класс python база данных в json формате!

class JsonDatabase:
    def __init__(self, db_file):
        self.db_file = db_file
        self.data = self.load_data()
        
    def load_data(self):
        try:
            with open(self.db_file, 'r') as f:
                data = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            data = {}
            return data
            
    def save_data(self):
        with open(self.db_file, 'w') as f:
            json.dump(self.data, f, indent=4)
            
    def get(self, key, default=None):
        return self.data.get(key, default)
        
    def set(self, key, value):
        self.data[key] = value
        self.save_data()
        
    def delete(self, key):
        if key in self.data:
            del self.data[key]
            self.save_data()
            
    def list_keys(self):
        return list(self.data.keys())
https://t.me/PyDevPro