Home > Mobile >  Can a text file be used as a Database for a server?
Can a text file be used as a Database for a server?

Time:08-25

I am making a simple server with Flask which is a REST-API.

The server only calculates some functions with the inputs sent by the client in the request and returns the results of the function to the client.

To calculate the functions theres no need to use any DataBase.

The Database in the server will only be used to validate the licence of the client. To do that I only need to save a dictionary like that: dataBase = {user_name0 : [rand_pass, hash_of_password, licence_date], ...}

Right now I am just creating this Database directly in the main.py file of my Flask api. The only other piece of data stored is an internal server password that I use to create tokens and I save it directly in the python file.

The problem of what I am doing is that adding new users or deleting them would imply stoping the server and editing the python file which really doesnt feel right. The think is that using a regular DataBase seems a little bit overkill in my situation because I only need a hashmap, theres only one single table, and I dont need queries.

What would be the best way to configure my DataBase? Can a basic text file with a json dic inside work, and then make the server update the dictionary somehow if theres changes to the file?

Another consideration is that I plan to edit the DataBase manually so no request will be able to edit it. The requests wont read the text in drive directly but just access the python dic. Can a script be created inside flask that when no traffic is present checks if theres changes in the file and if there are, then update the dictionary? If something like that is possible would it make sense for my particular needs?

CodePudding user response:

Yes, a JSON file as a database could work, but there are corner cases to think about, e.g. race conditions where different requests are concurrently reading and/or updating the file.

A better option for a small key-value database would be SQLite (even if you say "no need to use any DataBase" – it's built-in, and stores data in files anyway), which deals with all of those things for you; something like this (where keys are strings and values must be something that can be represented as JSON).

import sqlite3


class SQLiteKeyValueStore:
    def __init__(self, conn):
        self.conn = conn
        self.conn.execute("CREATE TABLE IF NOT EXISTS key_value (key TEXT PRIMARY KEY, value BLOB)")

    def get(self, key):
        cursor = self.conn.cursor()
        cursor.execute("SELECT value FROM key_value WHERE key=?", (key,))
        row = cursor.fetchone()
        if row is None:
            return None
        return json.loads(row[0])

    def set(self, key, value):
        cursor = self.conn.cursor()
        cursor.execute("INSERT OR REPLACE INTO key_value (key, value) VALUES (?, ?)", (key, json.dumps(value)))
        self.conn.commit()


def main():
    conn = sqlite3.connect("./foo.sqlite3")
    kvs = SQLiteKeyValueStore(conn)
    kvs.set("foo", "bar")
    print(kvs.get("foo"))


if __name__ == "__main__":
    main()
  • Related