· 9 years ago · Jan 30, 2017, 05:18 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(rc, result, name, data, callback=None)
46
47 self.local_save(self, name, data, test) # this works
48 self.local_save(name, data, test) # AttributeError: 'str' object has no attribute 'is_local'
49
50 @async_command
51 def local_save(self, name, data, callback=None, on_success=None):
52 """Save data locally.
53
54 Note: You must set the callback to self.on_save when you call this.
55 """
56 if not self.is_local:
57 raise S3DataObjectException("Not configured for local storage.")
58
59 save_dir = os.path.join(self.directory, 'test') # THIS IS TEMPORARY, PLEASE DONT LEAVE THAT HERE
60 if not os.path.exists(save_dir):
61 os.makedirs(save_dir)
62 path = os.path.join(save_dir, name)
63 with file(path, 'wb') as f:
64 f.write(data)
65 callback(0, None)
66
67 def on_save(self, rc, result, name, data, callback=None):
68 """If the save was successful, update the cache."""
69 if rc == 0: # success
70 self._cache[name] = data
71 if callback:
72 callback(rc, result)
73 else:
74 raise MyException("Failure saving.")
75
76
77if __name__ == '__main__':
78 test = MyObject()
79 print(test.is_local) # True
80 test.save('NAME', 'DATA')