persistency.py 1.97 KB
import json

"""
This module aims to manage environement variables local to the application.
These variables are persitent and located in a json file.
"""

class PersistencyData(object):
    """Initialize with an persistent file (json)

    You can access to environment variables using the brackets operators.
    You can also check with the 'in' operator if a key is present among
    the variables.
    
    example code:
    ```
    env = Env("myfile.json")

    if "MyVariable" in env:
        print(env["MyVariable"])
    else:
        env["MyVariable"] = "New value"
    ```

    """
    def __init__(self, file: str):
        self.__variables = {}
        self.file = file
        self.load()

    @property
    def variables(self):
        return self.__variables

    @property
    def file(self):
        return self.__file

    @file.setter
    def file(self, file):
        self.__file = file


    def set(self, key: str, value: str):
        """Modify an environment variable

        Args:
            key (str): [description]
            value ([type]): [description]
        """
        self.__variables[str]
        self.save()
    

    def get(self, key: str) -> str:
        """Get an environment variable.

        Args:
            key (str): [description]

        Returns:
            [str]: [description]
        """
        return self.variables[key]

    def __getitem__(self, key):
        print(key)
        return self.variables[key]

    def __setitem__(self, key, value):
        self.variables[key] = value

    def __delitem__(self, key):
        del self.variables[key]

    def __contains__(self, key):
        return key in self.variables
    
    def load(self):
        """Load the variables from the json file.
        """
        with open(self.file, "r") as f:
            self.__variables = json.load(f)


    def save(self):
        """Save the variables into the json file.
        """
        with open(self.file, "w") as f:
            json.dump(self.variables, f)