-
Notifications
You must be signed in to change notification settings - Fork 2k
/
create.py
428 lines (325 loc) · 13.3 KB
/
create.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import logging
from lib.plugins import lookup_package_plugin
import ckan.rating as ratings
from ckan.plugins import (PluginImplementations,
IGroupController,
IPackageController)
from ckan.logic import NotFound, ValidationError
from ckan.logic import check_access
from ckan.lib.base import _
import ckan.lib.dictization
from ckan.lib.dictization import model_dictize
from ckan.lib.dictization import model_save
from ckan.logic.schema import (
default_resource_schema,
default_create_relationship_schema,
default_create_vocabulary_schema,
default_create_activity_schema,
default_create_tag_schema)
from ckan.logic.schema import default_group_schema, default_user_schema
from ckan.lib.navl.dictization_functions import validate
from ckan.logic.action.update import _update_package_relationship
from ckan.logic.action import rename_keys, error_summary
from ckan import logic
log = logging.getLogger(__name__)
def package_create(context, data_dict):
model = context['model']
user = context['user']
model.Session.remove()
model.Session()._context = context
package_type = data_dict.get('type')
package_plugin = lookup_package_plugin(package_type)
try:
schema = package_plugin.form_to_db_schema_options({'type':'create',
'api':'api_version' in context})
except AttributeError:
schema = package_plugin.form_to_db_schema()
check_access('package_create', context, data_dict)
if 'api_version' not in context:
# old plugins do not support passing the schema so we need
# to ensure they still work
try:
package_plugin.check_data_dict(data_dict, schema)
except TypeError:
package_plugin.check_data_dict(data_dict)
data, errors = validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors, error_summary(errors))
rev = model.repo.new_revision()
rev.author = user
if 'message' in context:
rev.message = context['message']
else:
rev.message = _(u'REST API: Create object %s') % data.get("name")
pkg = model_save.package_dict_save(data, context)
admins = []
if user:
admins = [model.User.by_name(user.decode('utf8'))]
model.setup_default_user_roles(pkg, admins)
# Needed to let extensions know the package id
model.Session.flush()
for item in PluginImplementations(IPackageController):
item.create(pkg)
if not context.get('defer_commit'):
model.repo.commit()
## need to let rest api create
context["package"] = pkg
## this is added so that the rest controller can make a new location
context["id"] = pkg.id
log.debug('Created object %s' % str(pkg.name))
return model_dictize.package_dictize(pkg, context)
def package_create_validate(context, data_dict):
model = context['model']
schema = lookup_package_plugin().form_to_db_schema()
model.Session.remove()
model.Session()._context = context
check_access('package_create',context,data_dict)
data, errors = validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors, error_summary(errors))
else:
return data
def resource_create(context, data_dict):
#TODO This doesn't actually do anything
model = context['model']
user = context['user']
data, errors = validate(data_dict,
default_resource_schema(),
context)
def package_relationship_create(context, data_dict):
model = context['model']
user = context['user']
schema = context.get('schema') or default_create_relationship_schema()
api = context.get('api_version') or '1'
ref_package_by = 'id' if api == '2' else 'name'
id = data_dict['subject']
id2 = data_dict['object']
rel_type = data_dict['type']
comment = data_dict.get('comment', u'')
pkg1 = model.Package.get(id)
pkg2 = model.Package.get(id2)
if not pkg1:
raise NotFound('Subject package %r was not found.' % id)
if not pkg2:
return NotFound('Object package %r was not found.' % id2)
data, errors = validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors, error_summary(errors))
check_access('package_relationship_create', context, data_dict)
# Create a Package Relationship.
existing_rels = pkg1.get_relationships_with(pkg2, rel_type)
if existing_rels:
return _update_package_relationship(existing_rels[0],
comment, context)
rev = model.repo.new_revision()
rev.author = user
rev.message = _(u'REST API: Create package relationship: %s %s %s') % (pkg1, rel_type, pkg2)
rel = pkg1.add_relationship(rel_type, pkg2, comment=comment)
if not context.get('defer_commit'):
model.repo.commit_and_remove()
context['relationship'] = rel
relationship_dicts = rel.as_dict(ref_package_by=ref_package_by)
return relationship_dicts
def group_create(context, data_dict):
model = context['model']
user = context['user']
session = context['session']
schema = context.get('schema') or default_group_schema()
parent = context.get('parent', None)
check_access('group_create',context,data_dict)
data, errors = validate(data_dict, schema, context)
if errors:
session.rollback()
raise ValidationError(errors, error_summary(errors))
rev = model.repo.new_revision()
rev.author = user
if 'message' in context:
rev.message = context['message']
else:
rev.message = _(u'REST API: Create object %s') % data.get("name")
group = model_save.group_dict_save(data, context)
if parent:
parent_group = model.Group.get( parent )
if parent_group:
member = model.Member(group=parent_group, table_id=group.id, table_name='group')
session.add(member)
if user:
admins = [model.User.by_name(user.decode('utf8'))]
else:
admins = []
model.setup_default_user_roles(group, admins)
# Needed to let extensions know the group id
session.flush()
for item in PluginImplementations(IGroupController):
item.create(group)
activity_dict = {
'user_id': model.User.by_name(user.decode('utf8')).id,
'object_id': group.id,
'activity_type': 'new group',
}
activity_dict['data'] = {
'group': ckan.lib.dictization.table_dictize(group, context)
}
activity_create_context = {
'model': model,
'user': user,
'defer_commit':True,
'session': session
}
activity_create(activity_create_context, activity_dict, ignore_auth=True)
if not context.get('defer_commit'):
model.repo.commit()
context["group"] = group
context["id"] = group.id
log.debug('Created object %s' % str(group.name))
return model_dictize.group_dictize(group, context)
def rating_create(context, data_dict):
model = context['model']
user = context.get("user")
package_ref = data_dict.get('package')
rating = data_dict.get('rating')
opts_err = None
if not package_ref:
opts_err = _('You must supply a package id or name (parameter "package").')
elif not rating:
opts_err = _('You must supply a rating (parameter "rating").')
else:
try:
rating_int = int(rating)
except ValueError:
opts_err = _('Rating must be an integer value.')
else:
package = model.Package.get(package_ref)
if rating < ratings.MIN_RATING or rating > ratings.MAX_RATING:
opts_err = _('Rating must be between %i and %i.') % (ratings.MIN_RATING, ratings.MAX_RATING)
elif not package:
opts_err = _('Not found') + ': %r' % package_ref
if opts_err:
raise ValidationError(opts_err)
user = model.User.by_name(user)
ratings.set_rating(user, package, rating_int)
package = model.Package.get(package_ref)
ret_dict = {'rating average':package.get_average_rating(),
'rating count': len(package.ratings)}
return ret_dict
def user_create(context, data_dict):
'''Creates a new user'''
model = context['model']
schema = context.get('schema') or default_user_schema()
session = context['session']
check_access('user_create', context, data_dict)
data, errors = validate(data_dict, schema, context)
if errors:
session.rollback()
raise ValidationError(errors, error_summary(errors))
user = model_save.user_dict_save(data, context)
# Flush the session to cause user.id to be initialised, because
# activity_create() (below) needs it.
session.flush()
activity_create_context = {
'model': model,
'user': context['user'],
'defer_commit': True,
'session': session
}
activity_dict = {
'user_id': user.id,
'object_id': user.id,
'activity_type': 'new user',
}
activity_create(activity_create_context, activity_dict, ignore_auth=True)
if not context.get('defer_commit'):
model.repo.commit()
context['user'] = user
context['id'] = user.id
log.debug('Created user %s' % str(user.name))
return model_dictize.user_dictize(user, context)
## Modifications for rest api
def package_create_rest(context, data_dict):
api = context.get('api_version') or '1'
check_access('package_create_rest', context, data_dict)
dictized_package = model_save.package_api_to_dict(data_dict, context)
dictized_after = logic.get_action('package_create')(context, dictized_package)
pkg = context['package']
if api == '1':
package_dict = model_dictize.package_to_api1(pkg, context)
else:
package_dict = model_dictize.package_to_api2(pkg, context)
data_dict['id'] = pkg.id
return package_dict
def group_create_rest(context, data_dict):
api = context.get('api_version') or '1'
check_access('group_create_rest', context, data_dict)
dictized_group = model_save.group_api_to_dict(data_dict, context)
dictized_after = group_create(context, dictized_group)
group = context['group']
if api == '1':
group_dict = model_dictize.group_to_api1(group, context)
else:
group_dict = model_dictize.group_to_api2(group, context)
data_dict['id'] = group.id
return group_dict
def vocabulary_create(context, data_dict):
model = context['model']
schema = context.get('schema') or default_create_vocabulary_schema()
model.Session.remove()
model.Session()._context = context
check_access('vocabulary_create', context, data_dict)
data, errors = validate(data_dict, schema, context)
if errors:
model.Session.rollback()
raise ValidationError(errors, error_summary(errors))
vocabulary = model_save.vocabulary_dict_save(data, context)
if not context.get('defer_commit'):
model.repo.commit()
log.debug('Created Vocabulary %s' % str(vocabulary.name))
return model_dictize.vocabulary_dictize(vocabulary, context)
def activity_create(context, activity_dict, ignore_auth=False):
'''Create a new activity stream activity and return a dictionary
representation of it.
'''
model = context['model']
user = context['user']
# Any revision_id that the caller attempts to pass in the activity_dict is
# ignored and overwritten here.
if getattr(model.Session, 'revision', None):
activity_dict['revision_id'] = model.Session.revision.id
else:
activity_dict['revision_id'] = None
if not ignore_auth:
check_access('activity_create', context, activity_dict)
schema = context.get('schema') or default_create_activity_schema()
data, errors = validate(activity_dict, schema, context)
if errors:
raise ValidationError(errors)
activity = model_save.activity_dict_save(activity_dict, context)
if not context.get('defer_commit'):
model.repo.commit()
log.debug("Created '%s' activity" % activity.activity_type)
return model_dictize.activity_dictize(activity, context)
def package_relationship_create_rest(context, data_dict):
# rename keys
key_map = {'id': 'subject',
'id2': 'object',
'rel': 'type'}
# Don't be destructive to enable parameter values for
# object and type to override the URL parameters.
data_dict = rename_keys(data_dict, key_map, destructive=False)
relationship_dict = package_relationship_create(context, data_dict)
return relationship_dict
def tag_create(context, tag_dict):
'''Create a new tag and return a dictionary representation of it.'''
model = context['model']
check_access('tag_create', context, tag_dict)
schema = context.get('schema') or default_create_tag_schema()
data, errors = validate(tag_dict, schema, context)
if errors:
raise ValidationError(errors)
tag = model_save.tag_dict_save(tag_dict, context)
if not context.get('defer_commit'):
model.repo.commit()
log.debug("Created tag '%s' " % tag)
return model_dictize.tag_dictize(tag, context)