Public » MiniRedis Read More
Clone URL:  
Pushed to one repository · View In Graph Contained in tip

add saving and loading database

Changeset 4e30762c5ca3

Parent fe00d58e10cc

by Profile picture of Benjamin PollackBenjamin Pollack

Changes to 2 files · Browse files at 4e30762c5ca3 Showing diff from parent fe00d58e10cc Diff from another changeset...

Change 1 of 1 Show Entire File .gitignore Stacked
 
1
 
 
1
2
@@ -1,1 +1,2 @@
 *.swp +*.db
Change 1 of 6 Show Entire File miniredis.py Stacked
 
1
2
3
 
4
 
5
6
7
 
38
39
40
41
 
42
43
44
 
46
47
48
 
 
 
49
50
51
52
 
 
53
54
55
 
57
58
59
 
 
 
 
 
 
 
 
 
 
 
 
60
61
62
 
141
142
143
 
 
 
 
 
144
145
146
 
279
280
281
282
 
283
284
285
 
1
2
3
4
5
6
7
8
9
 
40
41
42
 
43
44
45
46
 
48
49
50
51
52
53
54
55
56
 
57
58
59
60
61
 
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
 
159
160
161
162
163
164
165
166
167
168
169
 
302
303
304
 
305
306
307
308
@@ -1,7 +1,9 @@
 #!/usr/bin/env python    import getopt +import os  import re +import pickle  import select  import socket  import sys @@ -38,7 +40,7 @@
  self.table = None    class MiniRedis(threading.Thread): - def __init__(self, host='127.0.0.1', port=56784, logging=False): + def __init__(self, host='127.0.0.1', port=56784, logging=False, db_file=None):   super(MiniRedis, self).__init__()   self.host = host   self.port = port @@ -46,10 +48,14 @@
  self.halt = True   self.tables = {}   self.clients = {} + self.db_file = db_file + + self.load()     def log(self, client, s):   if self.logging: - print '%s:%s: %s' % (client.socket.getpeername() + (s,)) + who = '%s:%s' % client.socket.getpeername() if client else 'SERVER' + print '%s: %s' % (who, s)     def select(self, client, db):   if db not in self.tables: @@ -57,6 +63,18 @@
  client.db = db   client.table = self.tables[db]   + def save(self): + if self.db_file: + with open(self.db_file, 'wb') as f: + pickle.dump(self.tables, f, pickle.HIGHEST_PROTOCOL) + self.log(None, 'saved database to "%s"' % self.db_file) + + def load(self): + if self.db_file and os.path.lexists(self.db_file): + with open(self.db_file, 'rb') as f: + self.tables = pickle.load(f) + self.log(None, 'loaded database from file "%s"' % self.db_file) +   def handle_set(self, client, key, data):   client.table[key] = data   self.log(client, 'SET %s -> %s' % (key, data)) @@ -141,6 +159,11 @@
  self.halt = True   return True   + def handle_save(self, client): + self.save() + self.log(client, 'SAVE') + return True +   def unwrap_set(self, client, line):   key, length = line.split()   data = client.rfile.read(int(length)) @@ -279,7 +302,7 @@
  elif o == '-l':   logging = True   print 'Launching MiniRedis on %s:%s' % (host, port) - m = MiniRedis(host=host, port=port, logging=logging) + m = MiniRedis(host=host, port=port, logging=logging, db_file='miniredis.db')   m.start()   m.join()   print 'Stopped'