persistency.py
1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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)