Как лучше всего хранить небольшой объем данных в BE (буквально 1 строка)?

В настоящее время я работаю над функционалом, в котором пользователи хотят сохранить одно сообщение в заголовке страницы, чтобы уведомить других о чем-то происходящем в системе. По сути, это заголовок, который может быть обновлен любым пользователем.

Поскольку этот заголовок должен быть показан каждому пользователю на сайте, я не могу хранить его в локальном хранилище или в таблице пользователя. Кроме того, это одна строка сообщения на одной странице, поэтому создавать целую таблицу базы данных для этого кажется совершенно глупым. Поэтому, чтобы добиться этой функциональности, я добавил json-файл в BE, который просто содержит это сообщение, и представление, которое позволяет пользователям редактировать этот файл. Я также поместил этот файл в gitignore, потому что изменение данных в нем не должно отражаться в git.

Эта система пока работает нормально, но когда я переразвертываю систему с помощью Docker, этот файл удаляется и перестраивается, теряя первоначальное сообщение. Есть ли лучший способ хранить и обновлять эти данные? Или какой-нибудь способ не потерять мои данные при переразвертывании?

userdata.json

{
   message: "Holiday tomorrow, please report any issues by 3."
}

Чтение данных в Django View

try:
    if not os.path.exists(USERDATA_FILE):
        # Create the file with default structure if it doesn't exist
        with open(USERDATA_FILE, "w") as file:
            json.dump({"message": "Hello World!"}, file, indent=4)

        with open(USERDATA_FILE, "r") as file:
            data = json.load(file)
except Exception as e:
     print("Error in reading data")

You should store this datum in your existing database, even if the overhead of writing a migration and table infrastructure seems excessive at first glance.

One critical reason here is that your Docker setup already has a database and it already has persistence. Adding local-file storage to a container comes with a mild amount of complexities, including managing filesystem permissions and separately backing up that file. Using the persistence store you already have takes this detail out of the system, and makes the whole thing easier to manage.

Relatedly, if you're ever looking at running multiple replicas of your system, having the banner be stored in a single database makes it easier to manage. If you deployed the container in Kubernetes, the persistence problem becomes harder (it's hard to get storage that's shared across container replicas); you could maybe inject it via a ConfigMap but you'd need to do Kubernetes-specific management to update it. You can also imagine deploying the application without a container but on multiple hosts for scale or redundancy, and there you'd need to copy the banner file to every host manually if it weren't stored somewhere centrally.

It's also easy to imagine setups where the same banner isn't shown to every user. Maybe you have multiple user groups, or multiple tenants sharing the application. If the banner is stored in a table then it's easy to add a migration to ALTER TABLE banner ADD COLUMN ... to add a group or tenant ID, but with your proposed file layout it's going to be trickier to change away from "show the same banner to everyone".

A typical best practice is to avoid mounting anything into your container, except configuration files if needed, and to avoid storing anything in local files. That would seem to apply here as well.

Вернуться на верх