-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbulk.py
More file actions
92 lines (68 loc) · 2.73 KB
/
bulk.py
File metadata and controls
92 lines (68 loc) · 2.73 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
91
92
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
import six
from syncano.exceptions import SyncanoValidationError, SyncanoValueError
class BaseBulkCreate(six.with_metaclass(ABCMeta)):
"""
Helper class for making bulk create;
Usage:
instances = ObjectBulkCreate(objects, manager).process()
"""
MAX_BATCH_SIZE = 50
@abstractmethod
def __init__(self, objects, manager):
self.objects = objects
self.manager = manager
self.response = None
self.validated = False
def validate(self):
if len(self.objects) > self.MAX_BATCH_SIZE:
raise SyncanoValueError('Only 50 objects can be created at once.')
def make_batch_request(self):
if not self.validated:
raise SyncanoValueError('Bulk create not validated')
self.response = self.manager.batch(*[o.save() for o in self.objects])
def update_response(self, content_reponse):
content_reponse.update(self.manager.properties)
def process(self):
self.validate()
self.make_batch_request()
return self.response
class ObjectBulkCreate(BaseBulkCreate):
def __init__(self, objects, manager):
super(ObjectBulkCreate, self).__init__(objects, manager)
def validate(self):
super(ObjectBulkCreate, self).validate()
class_names = []
instance_names = []
# mark objects as lazy & make some check btw;
for o in self.objects:
class_names.append(o.class_name)
instance_names.append(o.instance_name)
o.mark_for_batch()
if len(set(class_names)) != 1:
raise SyncanoValidationError('Bulk create can handle only objects of the same type.')
if len(set(instance_names)) != 1:
raise SyncanoValidationError('Bulk create can handle only one instance.')
self.validated = True
def update_response(self, content_reponse):
super(ObjectBulkCreate, self).update_response(content_reponse)
content_reponse.update(
{
'class_name': self.objects[0].class_name,
'instance_name': self.objects[0].instance_name
}
)
class ModelBulkCreate(BaseBulkCreate):
def __init__(self, objects, manager):
super(ModelBulkCreate, self).__init__(objects, manager)
def validate(self):
super(ModelBulkCreate, self).validate()
class_names = []
# mark objects as lazy & make some check btw;
for o in self.objects:
class_names.append(type(o))
o.mark_for_batch()
if len(set(class_names)) != 1:
raise SyncanoValidationError('Bulk create can handle only objects of the same type.')
self.validated = True