Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

KeyValueDB.py 2.6 KB

You have to be logged in to leave a comment. Sign In
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
  1. import traceback
  2. from datetime import datetime
  3. from pathlib import Path
  4. from ..io import FormattedFileIO
  5. class KeyValueDB:
  6. _KeyValueDB_VERSION = 1
  7. def __init__(self, filepath = None):
  8. """
  9. Simple key/value database.
  10. each key/value pickled/unpickled separately,
  11. thus unpickling error will not corrupt whole db
  12. filepath(None) if None, DB will not be saved on disk
  13. """
  14. self._filepath = Path(filepath) if filepath is not None else None
  15. self._save_timestamp = None
  16. try:
  17. d = {}
  18. if self._filepath is not None:
  19. with FormattedFileIO(self._filepath, 'r+') as f:
  20. ver, = f.read_fmt('I')
  21. if ver == KeyValueDB._KeyValueDB_VERSION:
  22. keys_len, = f.read_fmt('I')
  23. for i in range(keys_len):
  24. obj = f.read_pickled()
  25. if obj is not None:
  26. key, data = obj
  27. d[key] = data
  28. except:
  29. d = {}
  30. self._data = d
  31. def clear(self):
  32. self._data = {}
  33. def get_value(self, key, default_value=None):
  34. """
  35. returns data by key or None
  36. """
  37. return self._data.get(key, default_value)
  38. def set_value(self, key, value):
  39. """
  40. set value by key
  41. """
  42. self._data[key] = value
  43. if self._save_timestamp is None:
  44. # Save in 1 sec
  45. self._save_timestamp = datetime.now().timestamp() + 1.0
  46. def _save_data(self):
  47. if self._filepath is not None:
  48. try:
  49. with FormattedFileIO(self._filepath, 'w+') as f:
  50. f.write_fmt('I', KeyValueDB._KeyValueDB_VERSION)
  51. d = self._data
  52. keys = list(d.keys())
  53. f.write_fmt('I', len(keys))
  54. for key in keys:
  55. f.write_pickled( (key, d[key]) )
  56. f.truncate()
  57. except:
  58. print(f'Unable to save the data. {traceback.format_exc()}')
  59. def finish_pending_jobs(self):
  60. """finish any pending jobs now"""
  61. if self._save_timestamp is not None:
  62. self._save_timestamp = None
  63. self._save_data()
  64. def process_messages(self):
  65. save_timestamp = self._save_timestamp
  66. if save_timestamp is not None and \
  67. (datetime.now().timestamp() - save_timestamp) >= 0:
  68. self._save_timestamp = None
  69. self._save_data()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...