-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
244 lines (200 loc) · 6.66 KB
/
utils.py
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"""
Utilities for creating dynamic models.
Usage is similar to this::
mymodel = simple_geomodel("MyModel", managed=False, db_table='my_model',
mychar = simple_geofield("CharField", max_length=255, default=''),
mygeom = simple_geofield("PolygonField", srid=3157, null=True),
...
)
declare_model(mymodel)
"""
from django.conf import settings
import importlib
import sys
def method(method, *parameters):
return {
'method' : method,
'parameters' : parameters
}
def queryset(module, model, *extra):
return {
"type" : "queryset",
"module" : module,
"model" : model,
"extra" : extra
}
def attribs(module, *ls):
return {
"type" : 'attribs',
"module" : module,
"ls" : ls
}
def callable(module, name, *args, **kwargs):
return {
"type" : "callable",
"module" : module,
"callable" : name,
"parameters" : { "positionals" : args, "keywords" : kwargs }
}
def attribute(module, name):
return {
"type" : "attribute",
"module" : module,
"attribute" : name
}
def class_attribute(module, cls, attribute):
return {
"type" : "class_attribute",
"module" : module,
"cls" : cls,
"attribute" : attribute
}
def class_method(module, cls, method, *args, **kwargs):
return {
"type" : "class_method",
"module" : module,
"cls" : cls,
"method" : method,
"parameters" : { "positionals" : args, "keywords" : kwargs }
}
def model(name, bases, fields, **meta):
for key, value in meta.items():
if value is None:
del meta[key]
if not isinstance(bases, list):
bases = [bases]
return {
"name" : name,
"bases" : bases,
"fields" : fields,
"meta" : meta
}
def resource(name, bases, fields, **meta):
for key, value in meta.items():
if value is None:
del meta[key]
if not isinstance(bases, list):
bases = [bases]
return {
"name" : name,
"bases" : bases,
"fields" : fields,
"meta" : meta
}
def simple_model_resource(module, model, resource_name, **meta):
meta['queryset'] = queryset(module, model, method('all', []))
meta['resource_name'] = resource_name
return resource(model, attribute('tastypie.resources', 'ModelResource'), {}, **meta)
def simple_geo_resource(module, model, resource_name, **meta):
meta['queryset'] = queryset(module, model, method('all', []))
meta['resource_name'] = resource_name
return resource(model, attribute('ga_ows.tastyhacks', 'GeoResource'), {}, **meta)
def simple_geomodel(name, managed=True, db_table=None, **fields):
fields['objects'] = callable("django.contrib.gis.db.models", "GeoManager")
return model(
name,
attribute('django.contrib.gis.db.models', 'Model'),
fields,
managed=managed,
db_table=db_table,
app_label='ga_dynamic_models'
)
def simple_model(name, managed=True, db_table=None, **fields):
return model(
name,
attribute('django.db.models', 'Model'),
fields,
managed=managed,
db_table=db_table,
app_label='ga_dynamic_models'
)
def simple_field(kind, *args, **kwargs):
return {
"type" : "callable",
"module" : 'django.db.models',
"callable" : kind,
"parameters" : { 'positionals' : args, 'keywords' : kwargs }
}
def simple_geofield(kind, *args, **kwargs):
return {
"type" : "callable",
"module" : 'django.contrib.gis.db.models',
"callable" : kind,
"parameters" : { 'positionals' : args, 'keywords' : kwargs }
}
def declare_model(model, replace=False, user=None, syncdb=False):
model['_id'] = model['name']
_db = get_connection()
if user:
model['_owner'] = user.pk
else:
model['_owner'] = None
one = _db['ga_dynamic_models__models'].find_one(model['name'], fields=['_id', '_owner'])
print "found old model"
if not one:
_db['ga_dynamic_models__models'].insert(model, safe=True)
elif replace and ((not one['owner']) or user.pk == one['owner']):
_db['ga_dynamic_models__models'].save(model, safe=True)
else:
raise Exception("Cannot insert model record")
print "inserted new model"
print "syncdb"
if syncdb:
m = get_model(model['name'])
from django.core.management import call_command
call_command('syncdb', noinput=True)
print "syncdb finished"
def drop_resource(model, user=None):
_db = get_connection()
if isinstance(model, str) or isinstance(model, unicode):
one = _db['ga_dynamic_models__api'].find_one(model, fields=['_id', '_owner'])
else:
one = _db['ga_dynamic_models__api'].find_one(model['name'], fields=['_id', '_owner'])
if one:
if '_owner' not in one or not one['_owner'] or one['_owner'] == user.pk:
_db['ga_dynamic_models__api'].remove(model)
else:
raise Exception("Cannot delete resource record")
def declare_resource(model, replace=False, user=None):
model['_id'] = model['name']
_db = get_connection()
if user:
model['_owner'] = user.pk
else:
model['_owner'] = None
one = _db['ga_dynamic_models__api'].find_one(model['name'], fields=['_id', '_owner'])
if not one:
_db['ga_dynamic_models__api'].insert(model, safe=True)
elif replace and ((not one['_owner']) or user.pk == one['_owner']):
_db['ga_dynamic_models__api'].save(model, safe=True)
else:
raise Exception("Cannot insert resource record")
def drop_model(model, user=None):
_db = get_connection()
one = _db['ga_dynamic_models__models'].find_one(model, fields=['_id', 'owner'])
if one:
if '_owner' not in one or not one['_owner'] or one['_owner'] == user.pk:
_db['ga_dynamic_models__models'].remove(model)
try:
m = get_model(model)
m.objects.all().delete()
except AttributeError:
pass
else:
raise Exception("Cannot delete model record")
def get_connection():
if 'ga_dynamic_models' in settings.MONGODB_ROUTES:
_db = settings.MONGODB_ROUTES['ga_dynamic_models']
else:
_db = settings.MONGODB_ROUTES['default']
return _db
def get_model(model):
try:
del sys.modules['ga_dynamic_models.models']
except KeyError:
pass
models = importlib.import_module('ga_dynamic_models.models')
if hasattr(models, model):
return models.__getattribute__(model)
else:
raise AttributeError("No such model")