author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Fri, 29 May 2009 21:34:09 +0200 | |
changeset 2015 | 3009899e1e51 |
parent 1977 | 606923dff11b |
child 2255 | c346af0727ca |
permissions | -rw-r--r-- |
0 | 1 |
"""The edit controller, handling form submitting. |
2 |
||
3 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1948
diff
changeset
|
4 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1948
diff
changeset
|
6 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 7 |
""" |
8 |
__docformat__ = "restructuredtext en" |
|
1948 | 9 |
|
0 | 10 |
from decimal import Decimal |
11 |
||
12 |
from rql.utils import rqlvar_maker |
|
13 |
||
14 |
from cubicweb import Binary, ValidationError, typed_eid |
|
15 |
from cubicweb.web import INTERNAL_FIELD_VALUE, RequestError, NothingToEdit |
|
16 |
from cubicweb.web.controller import parse_relations_descr |
|
17 |
from cubicweb.web.views.basecontrollers import ViewController |
|
18 |
||
19 |
||
20 |
class ToDoLater(Exception): |
|
21 |
"""exception used in the edit controller to indicate that a relation |
|
22 |
can't be handled right now and have to be handled later |
|
23 |
""" |
|
24 |
||
25 |
class EditController(ViewController): |
|
26 |
id = 'edit' |
|
27 |
||
28 |
def publish(self, rset=None, fromjson=False): |
|
29 |
"""edit / create / copy / delete entity / relations""" |
|
30 |
self.fromjson = fromjson |
|
884 | 31 |
for key in self.req.form: |
0 | 32 |
# There should be 0 or 1 action |
33 |
if key.startswith('__action_'): |
|
34 |
cbname = key[1:] |
|
35 |
try: |
|
36 |
callback = getattr(self, cbname) |
|
37 |
except AttributeError: |
|
884 | 38 |
raise RequestError(self.req._('invalid action %r' % key)) |
0 | 39 |
else: |
40 |
return callback() |
|
41 |
self._default_publish() |
|
42 |
self.reset() |
|
43 |
||
44 |
def _default_publish(self): |
|
45 |
req = self.req |
|
46 |
form = req.form |
|
47 |
# no specific action, generic edition |
|
48 |
self._to_create = req.data['eidmap'] = {} |
|
49 |
self._pending_relations = [] |
|
50 |
todelete = self.req.get_pending_deletes() |
|
51 |
toinsert = self.req.get_pending_inserts() |
|
52 |
try: |
|
53 |
methodname = form.pop('__method', None) |
|
54 |
for eid in req.edited_eids(): |
|
55 |
formparams = req.extract_entity_params(eid) |
|
56 |
if methodname is not None: |
|
57 |
entity = req.eid_rset(eid).get_entity(0, 0) |
|
58 |
method = getattr(entity, methodname) |
|
59 |
method(formparams) |
|
60 |
eid = self.edit_entity(formparams) |
|
61 |
except (RequestError, NothingToEdit): |
|
62 |
if '__linkto' in form and 'eid' in form: |
|
63 |
self.execute_linkto() |
|
64 |
elif not ('__delete' in form or '__insert' in form or todelete or toinsert): |
|
65 |
raise ValidationError(None, {None: req._('nothing to edit')}) |
|
66 |
# handle relations in newly created entities |
|
67 |
if self._pending_relations: |
|
68 |
for rschema, formparams, x, entity in self._pending_relations: |
|
69 |
self.handle_relation(rschema, formparams, x, entity, True) |
|
1753 | 70 |
|
0 | 71 |
# XXX this processes *all* pending operations of *all* entities |
72 |
if form.has_key('__delete'): |
|
73 |
todelete += req.list_form_param('__delete', form, pop=True) |
|
74 |
if todelete: |
|
75 |
self.delete_relations(parse_relations_descr(todelete)) |
|
76 |
if form.has_key('__insert'): |
|
77 |
toinsert = req.list_form_param('__insert', form, pop=True) |
|
78 |
if toinsert: |
|
79 |
self.insert_relations(parse_relations_descr(toinsert)) |
|
80 |
self.req.remove_pending_operations() |
|
1753 | 81 |
|
0 | 82 |
def edit_entity(self, formparams, multiple=False): |
83 |
"""edit / create / copy an entity and return its eid""" |
|
84 |
etype = formparams['__type'] |
|
85 |
entity = self.vreg.etype_class(etype)(self.req, None, None) |
|
86 |
entity.eid = eid = self._get_eid(formparams['eid']) |
|
87 |
edited = self.req.form.get('__maineid') == formparams['eid'] |
|
88 |
# let a chance to do some entity specific stuff. |
|
1753 | 89 |
entity.pre_web_edit() |
0 | 90 |
# create a rql query from parameters |
91 |
self.relations = [] |
|
92 |
self.restrictions = [] |
|
93 |
# process inlined relations at the same time as attributes |
|
94 |
# this is required by some external source such as the svn source which |
|
95 |
# needs some information provided by those inlined relation. Moreover |
|
96 |
# this will generate less write queries. |
|
97 |
for rschema in entity.e_schema.subject_relations(): |
|
98 |
if rschema.is_final(): |
|
99 |
self.handle_attribute(entity, rschema, formparams) |
|
100 |
elif rschema.inlined: |
|
101 |
self.handle_inlined_relation(rschema, formparams, entity) |
|
102 |
execute = self.req.execute |
|
103 |
if eid is None: # creation or copy |
|
1753 | 104 |
if self.relations: |
0 | 105 |
rql = 'INSERT %s X: %s' % (etype, ','.join(self.relations)) |
106 |
else: |
|
107 |
rql = 'INSERT %s X' % etype |
|
108 |
if self.restrictions: |
|
109 |
rql += ' WHERE %s' % ','.join(self.restrictions) |
|
110 |
try: |
|
1753 | 111 |
# get the new entity (in some cases, the type might have |
0 | 112 |
# changed as for the File --> Image mutation) |
113 |
entity = execute(rql, formparams).get_entity(0, 0) |
|
114 |
eid = entity.eid |
|
115 |
except ValidationError, ex: |
|
116 |
# ex.entity may be an int or an entity instance |
|
117 |
self._to_create[formparams['eid']] = ex.entity |
|
118 |
if self.fromjson: |
|
119 |
ex.entity = formparams['eid'] |
|
120 |
raise |
|
121 |
self._to_create[formparams['eid']] = eid |
|
122 |
elif self.relations: # edition of an existant entity |
|
123 |
varmaker = rqlvar_maker() |
|
124 |
var = varmaker.next() |
|
125 |
while var in formparams: |
|
126 |
var = varmaker.next() |
|
127 |
rql = 'SET %s WHERE X eid %%(%s)s' % (','.join(self.relations), var) |
|
128 |
if self.restrictions: |
|
129 |
rql += ', %s' % ','.join(self.restrictions) |
|
130 |
formparams[var] = eid |
|
131 |
execute(rql, formparams) |
|
132 |
for rschema in entity.e_schema.subject_relations(): |
|
133 |
if rschema.is_final() or rschema.inlined: |
|
134 |
continue |
|
135 |
self.handle_relation(rschema, formparams, 'subject', entity) |
|
136 |
for rschema in entity.e_schema.object_relations(): |
|
137 |
if rschema.is_final(): |
|
138 |
continue |
|
139 |
self.handle_relation(rschema, formparams, 'object', entity) |
|
140 |
if edited: |
|
141 |
self.notify_edited(entity) |
|
142 |
if formparams.has_key('__delete'): |
|
143 |
todelete = self.req.list_form_param('__delete', formparams, pop=True) |
|
144 |
self.delete_relations(parse_relations_descr(todelete)) |
|
145 |
if formparams.has_key('__cloned_eid'): |
|
146 |
entity.copy_relations(formparams['__cloned_eid']) |
|
147 |
if formparams.has_key('__insert'): |
|
148 |
toinsert = self.req.list_form_param('__insert', formparams, pop=True) |
|
149 |
self.insert_relations(parse_relations_descr(toinsert)) |
|
150 |
if edited: # only execute linkto for the main entity |
|
151 |
self.execute_linkto(eid) |
|
152 |
return eid |
|
153 |
||
154 |
def _action_apply(self): |
|
155 |
self._default_publish() |
|
156 |
self.reset() |
|
1753 | 157 |
|
0 | 158 |
def _action_cancel(self): |
159 |
errorurl = self.req.form.get('__errorurl') |
|
160 |
if errorurl: |
|
161 |
self.req.cancel_edition(errorurl) |
|
162 |
return self.reset() |
|
163 |
||
164 |
def _action_delete(self): |
|
165 |
self.delete_entities(self.req.edited_eids(withtype=True)) |
|
166 |
return self.reset() |
|
167 |
||
1162
f210dce0dc47
fix for booelan attribute which have empty string as false value and didn't work if default value for this attribute was True.
Stephanie Marcu <stephanie.marcu@logilab.fr>
parents:
0
diff
changeset
|
168 |
def _needs_edition(self, rtype, formparams, entity): |
0 | 169 |
"""returns True and and the new value if `rtype` was edited""" |
170 |
editkey = 'edits-%s' % rtype |
|
171 |
if not editkey in formparams: |
|
172 |
return False, None # not edited |
|
173 |
value = formparams.get(rtype) or None |
|
1162
f210dce0dc47
fix for booelan attribute which have empty string as false value and didn't work if default value for this attribute was True.
Stephanie Marcu <stephanie.marcu@logilab.fr>
parents:
0
diff
changeset
|
174 |
if entity.has_eid() and (formparams.get(editkey) or None) == value: |
0 | 175 |
return False, None # not modified |
176 |
if value == INTERNAL_FIELD_VALUE: |
|
1753 | 177 |
value = None |
0 | 178 |
return True, value |
179 |
||
180 |
def handle_attribute(self, entity, rschema, formparams): |
|
181 |
"""append to `relations` part of the rql query to edit the |
|
182 |
attribute described by the given schema if necessary |
|
183 |
""" |
|
184 |
attr = rschema.type |
|
1162
f210dce0dc47
fix for booelan attribute which have empty string as false value and didn't work if default value for this attribute was True.
Stephanie Marcu <stephanie.marcu@logilab.fr>
parents:
0
diff
changeset
|
185 |
edition_needed, value = self._needs_edition(attr, formparams, entity) |
0 | 186 |
if not edition_needed: |
187 |
return |
|
188 |
# test if entity class defines a special handler for this attribute |
|
189 |
custom_edit = getattr(entity, 'custom_%s_edit' % attr, None) |
|
190 |
if custom_edit: |
|
191 |
custom_edit(formparams, value, self.relations) |
|
192 |
return |
|
193 |
attrtype = rschema.objects(entity.e_schema)[0].type |
|
194 |
# on checkbox or selection, the field may not be in params |
|
195 |
if attrtype == 'Boolean': |
|
196 |
value = bool(value) |
|
197 |
elif attrtype == 'Decimal': |
|
198 |
value = Decimal(value) |
|
199 |
elif attrtype == 'Bytes': |
|
200 |
# if it is a file, transport it using a Binary (StringIO) |
|
907 | 201 |
# XXX later __detach is for the new widget system, the former is to |
202 |
# be removed once web/widgets.py has been dropped |
|
203 |
if formparams.has_key('__%s_detach' % attr) or formparams.has_key('%s__detach' % attr): |
|
0 | 204 |
# drop current file value |
205 |
value = None |
|
1101
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
907
diff
changeset
|
206 |
# no need to check value when nor explicit detach nor new file |
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
907
diff
changeset
|
207 |
# submitted, since it will think the attribute is not modified |
0 | 208 |
elif isinstance(value, unicode): |
209 |
# file modified using a text widget |
|
1360
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
210 |
encoding = entity.attr_metadata(attr, 'encoding') |
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
211 |
value = Binary(value.encode(encoding)) |
1765
a25c7c73c8f6
check a file is submitted first
sylvain.thenault@logilab.fr
parents:
1753
diff
changeset
|
212 |
elif value: |
1361
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
213 |
# value is a 3-uple (filename, mimetype, stream) |
0 | 214 |
val = Binary(value[2].read()) |
215 |
if not val.getvalue(): # usually an unexistant file |
|
216 |
value = None |
|
217 |
else: |
|
218 |
val.filename = value[0] |
|
1361
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
219 |
# ignore browser submitted MIME type since it may be buggy |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
220 |
# XXX add a config option to tell if we should consider it |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
221 |
# or not? |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
222 |
#if entity.e_schema.has_metadata(attr, 'format'): |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
223 |
# key = '%s_format' % attr |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
224 |
# formparams[key] = value[1] |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
225 |
# self.relations.append('X %s_format %%(%s)s' |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
226 |
# % (attr, key)) |
1101
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
907
diff
changeset
|
227 |
# XXX suppose a File compatible schema |
0 | 228 |
if entity.e_schema.has_subject_relation('name') \ |
229 |
and not formparams.get('name'): |
|
230 |
formparams['name'] = value[0] |
|
231 |
self.relations.append('X name %(name)s') |
|
232 |
value = val |
|
1940
2565aae48d48
fix so that one can edit an entity with a Bytes field without specifying a new file
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1802
diff
changeset
|
233 |
else: |
2565aae48d48
fix so that one can edit an entity with a Bytes field without specifying a new file
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1802
diff
changeset
|
234 |
# no specified value, skip |
2565aae48d48
fix so that one can edit an entity with a Bytes field without specifying a new file
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1802
diff
changeset
|
235 |
return |
0 | 236 |
elif value is not None: |
237 |
if attrtype in ('Date', 'Datetime', 'Time'): |
|
238 |
try: |
|
239 |
value = self.parse_datetime(value, attrtype) |
|
240 |
except ValueError: |
|
241 |
raise ValidationError(entity.eid, |
|
242 |
{attr: self.req._("invalid date")}) |
|
243 |
elif attrtype == 'Password': |
|
244 |
# check confirmation (see PasswordWidget for confirmation field name) |
|
245 |
confirmval = formparams.get(attr + '-confirm') |
|
246 |
if confirmval != value: |
|
247 |
raise ValidationError(entity.eid, |
|
248 |
{attr: self.req._("password and confirmation don't match")}) |
|
249 |
# password should *always* be utf8 encoded |
|
250 |
value = value.encode('UTF8') |
|
251 |
else: |
|
252 |
# strip strings |
|
253 |
value = value.strip() |
|
254 |
elif attrtype == 'Password': |
|
255 |
# skip None password |
|
256 |
return # unset password |
|
257 |
formparams[attr] = value |
|
258 |
self.relations.append('X %s %%(%s)s' % (attr, attr)) |
|
259 |
||
260 |
def _relation_values(self, rschema, formparams, x, entity, late=False): |
|
261 |
"""handle edition for the (rschema, x) relation of the given entity |
|
262 |
""" |
|
263 |
rtype = rschema.type |
|
264 |
editkey = 'edit%s-%s' % (x[0], rtype) |
|
265 |
if not editkey in formparams: |
|
266 |
return # not edited |
|
267 |
try: |
|
268 |
values = self._linked_eids(self.req.list_form_param(rtype, formparams), late) |
|
269 |
except ToDoLater: |
|
270 |
self._pending_relations.append((rschema, formparams, x, entity)) |
|
271 |
return |
|
272 |
origvalues = set(typed_eid(eid) for eid in self.req.list_form_param(editkey, formparams)) |
|
273 |
return values, origvalues |
|
274 |
||
275 |
def handle_inlined_relation(self, rschema, formparams, entity, late=False): |
|
276 |
"""handle edition for the (rschema, x) relation of the given entity |
|
277 |
""" |
|
278 |
try: |
|
279 |
values, origvalues = self._relation_values(rschema, formparams, |
|
280 |
'subject', entity, late) |
|
281 |
except TypeError: |
|
282 |
return # not edited / to do later |
|
283 |
if values == origvalues: |
|
284 |
return # not modified |
|
285 |
attr = str(rschema) |
|
286 |
if values: |
|
287 |
formparams[attr] = iter(values).next() |
|
288 |
self.relations.append('X %s %s' % (attr, attr.upper())) |
|
289 |
self.restrictions.append('%s eid %%(%s)s' % (attr.upper(), attr)) |
|
290 |
elif entity.has_eid(): |
|
291 |
self.handle_relation(rschema, formparams, 'subject', entity, late) |
|
1753 | 292 |
|
0 | 293 |
def handle_relation(self, rschema, formparams, x, entity, late=False): |
294 |
"""handle edition for the (rschema, x) relation of the given entity |
|
295 |
""" |
|
296 |
try: |
|
297 |
values, origvalues = self._relation_values(rschema, formparams, x, |
|
298 |
entity, late) |
|
299 |
except TypeError: |
|
300 |
return # not edited / to do later |
|
301 |
etype = entity.e_schema |
|
302 |
if values == origvalues: |
|
303 |
return # not modified |
|
304 |
if x == 'subject': |
|
305 |
desttype = rschema.objects(etype)[0] |
|
306 |
card = rschema.rproperty(etype, desttype, 'cardinality')[0] |
|
307 |
subjvar, objvar = 'X', 'Y' |
|
308 |
else: |
|
309 |
desttype = rschema.subjects(etype)[0] |
|
310 |
card = rschema.rproperty(desttype, etype, 'cardinality')[1] |
|
311 |
subjvar, objvar = 'Y', 'X' |
|
312 |
eid = entity.eid |
|
313 |
if x == 'object' or not rschema.inlined or not values: |
|
314 |
# this is not an inlined relation or no values specified, |
|
315 |
# explicty remove relations |
|
1798
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
316 |
rql = 'DELETE %s %s %s WHERE X eid %%(x)s, Y eid %%(y)s' % ( |
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
317 |
subjvar, rschema, objvar) |
0 | 318 |
for reid in origvalues.difference(values): |
319 |
self.req.execute(rql, {'x': eid, 'y': reid}, ('x', 'y')) |
|
1798
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
320 |
seteids = values.difference(origvalues) |
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
321 |
if seteids: |
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
322 |
rql = 'SET %s %s %s WHERE X eid %%(x)s, Y eid %%(y)s' % ( |
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
323 |
subjvar, rschema, objvar) |
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
324 |
for reid in seteids: |
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
325 |
self.req.execute(rql, {'x': eid, 'y': reid}, ('x', 'y')) |
1753 | 326 |
|
0 | 327 |
def _get_eid(self, eid): |
328 |
# should be either an int (existant entity) or a variable (to be |
|
329 |
# created entity) |
|
330 |
assert eid or eid == 0, repr(eid) # 0 is a valid eid |
|
331 |
try: |
|
332 |
return typed_eid(eid) |
|
333 |
except ValueError: |
|
334 |
try: |
|
335 |
return self._to_create[eid] |
|
336 |
except KeyError: |
|
337 |
self._to_create[eid] = None |
|
338 |
return None |
|
339 |
||
340 |
def _linked_eids(self, eids, late=False): |
|
341 |
"""return a list of eids if they are all known, else raise ToDoLater |
|
342 |
""" |
|
343 |
result = set() |
|
344 |
for eid in eids: |
|
345 |
if not eid: # AutoCompletionWidget |
|
346 |
continue |
|
347 |
eid = self._get_eid(eid) |
|
348 |
if eid is None: |
|
349 |
if not late: |
|
350 |
raise ToDoLater() |
|
351 |
# eid is still None while it's already a late call |
|
352 |
# this mean that the associated entity has not been created |
|
353 |
raise Exception('duh') |
|
354 |
result.add(eid) |
|
355 |
return result |
|
356 |
||
1753 | 357 |