· 9 years ago · Jan 30, 2017, 05:06 PM
1def async_command(func):
2 """Decorator to setup weird async boilerplate code"""
3 @wraps(func, assigned=('__name__', '__module__'), updated=())
4 class Command(object):
5 def __init__(self, *args, **kwargs):
6 print("ARGS")
7 print(self)
8 print(args)
9 self.is_done = False
10 if 'callback' in kwargs:
11 self.callback = kwargs.get('callback')
12 elif len(args) > 0:
13 self.callback = args[0]
14 else:
15 self.callback = None
16 func(on_success=self.on_success, *args, **kwargs)
17
18 def on_success(self, rc, result):
19 self.is_done = True
20 if self.callback:
21 self.callback(rc, result)
22
23 return Command
24
25
26class MyObject(object):
27
28 is_local = CONFIG.is_local
29 access_key = CONFIG.access_key
30 secret_key = CONFIG.secret_key
31 region_default = CONFIG.region
32 bucket = CONFIG.bucket
33 directory = CONFIG.directory
34
35 _cache = {} # Cache everything we load
36
37 def __init__(self):
38 pass
39
40 def save(self, name, data):
41 """Save the object."""
42 # on_save = functools.partial(self.on_save, name=name, data=data)
43
44 def test(rc, result):
45 self.on_save(self, rc, result, name, data, callback=None)
46
47 self.local_save(name, data, test)
48
49 @async_command
50 def local_save(self, name, data, callback=None, on_success=None):
51 """Save data locally.
52
53 Note: You must set the callback to self.on_save when you call this.
54 """
55 if not self.is_local: # AttributeError: 'str' object has no attribute 'is_local'
56 raise S3DataObjectException("Not configured for local storage.")
57
58 save_dir = os.path.join(self.directory, 'test') # THIS IS TEMPORARY, PLEASE DONT LEAVE THAT HERE
59 if not os.path.exists(save_dir):
60 os.makedirs(save_dir)
61 path = os.path.join(save_dir, name)
62 with file(path, 'wb') as f:
63 f.write(data)
64 callback(0, None)
65
66 def on_save(self, rc, result, name, data, callback=None):
67 """If the save was successful, update the cache."""
68 if rc == 0: # success
69 self._cache[name] = data
70 if callback:
71 callback(rc, result)
72 else:
73 raise MyException("Failure saving.")
74
75
76if __name__ == '__main__':
77 test = MyObject()
78 print(test.is_local) # True
79 test.save('NAME', 'DATA')