A better Json backup file ( showcase )

Honestly I already did this once but it only has the save function and its complicated ( I guess )
so I remade it into a few functions. Obviously for their own uses
incase your database absolutely got trashed on by your friend Joe_Destroys_Everything_Even_Databases
then you can absolutely welcome this new Json database
I even use it in my template https://replit.com/@Idkwhttph/Python-Template-all-you-need?v=1

import json

import os

from replit import db

backup_file_path = 'backup.json'

def create_backup():

  backup_data = dict(db)
  
  with open(backup_file_path, 'w') as file:
    json.dump(backup_data, file, indent = 2)
      

def load_backup():
  if os.path.exists(backup_file_path):
    with open(backup_file_path, 'r') as file:
      backup_data = json.load(file)
      db.update(backup_data)


def save_backup():
  backup_data = dict(db)
  
  with open(backup_file_path, 'w') as file:
    json.dump(backup_data, file)


def sync_backup():
    with open(backup_file_path, 'r') as file:
        backup_data = json.load(file)
    
    db.update(backup_data)
    
    create_backup()

#How to use:
#This Json.py is used for backup databases. This can be helpful if you want to manipulate data in your database and it is easier since you can access it directly. And not print(db) and db['whatever'] = 'whatever'.
#First, do create_backup() to create a new Json Backup File.
#After you have done that, if you want to load the data into the replit db, do load_backup()
#Use the save_backup() if you want to save things to the database.
# sync the backup file with the replit file with sync_backup().

I hope you enjoy this showcase and I hope you welcome this block of code into your python code.
Not only is it good to keep your friend Joe_Destroys_Everything_Even_Databases at bay, it can also help visualise the data better since you would have to just do
print(db.keys()) and whatever. instead, you can add data to the database WITH the Json File instead of db[‘Joe_Wants_Milk’] = 5423482347283472384723847284238

1 Like

Did you know that replit dB’s code is very similar to your code, and it would be easier to modify replitDB’s code to have a backup method. It’s just another Python program

1 Like

It’s a good idea to back up a ReplDB since we don’t have access to the place it’s stored. That’s part of why I try to avoid it if I can. Now I’m learning effective JSON usage in Python.

1 Like

Yes, that is quite true. To complement that, you can also modify the venv/lib/python3.x/replit/database/*.py files to your liking, such as to include the ability to support execution by non-replit users and auto-backups to a customized file when used.
Here is the modified version of replDB that I like to use:

let me retrieve it first
3 Likes