formbar / formbar / form.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
import logging
import datetime
import sqlalchemy as sa
from formencode import htmlfill

from formbar.fahelpers import get_fieldset, get_data
from formbar.renderer import FormRenderer, get_renderer

log = logging.getLogger(__name__)


class Error(Exception):
    """Base class for exceptions in this module."""
    pass


class StateError(Error):
    """Exception raised for state errors while processing the form.

        :msg:  explanation of the error
    """

    def __init__(self, msg):
        self.msg = msg


class Validator(object):
    """Docstring for Validator """

    def __init__(self, field, error, callback):
        """@todo: to be defined

        :field: @todo
        :error: @todo
        :callback: @todo

        """
        self._field = field
        self._error = error
        self._callback = callback

    def check(self, data):
        return self._callback(self._field, data)


class Form(object):
    """Class for forms. The form will take care for rendering the form,
    validating the submitted data and saving the data back to the
    item.

    The form must be instanciated with an instance of an ``Form``
    configuration and optional an SQLAlchemy mapped item.

    If an SQLAlchemy mapped item is provided there are some basic
    validation is done based on the defintion in the database. Further
    the save method will save the values directly into the database.

    If no item was provided than a dummy item will be created with the
    attributes of the configured fields in the form.
    """

    def __init__(self, config, item=None, dbsession=None, translate=None,
                 change_page_callback={}, renderers={}):
        """Initialize the form with ``Form`` configuration instance and
        optional an SQLAlchemy mapped object.

        :config: FormConfiguration.
        :item: SQLAlchemy mapped instance
        :dbsession: dbsession
        :translate: Translation function which returns a translated
        string for a given msgid
        :set_page_callback: Url which will be called when the user
        changes the currently selected page.
        :renderers: A optional dictionary of custom renderers which are
        provided to the form to render specific form elements. The key
        is the type of the renderer as named in the formular
        configuration.

        """
        self._config = config
        self._item = item
        self._dbsession = dbsession
        if translate:
            self._translate = translate
        else:
            self._translate = lambda msgid: msgid

        self.fs = get_fieldset(item, config, dbsession)
        """FormAlchemy fieldset"""
        self.data = get_data(self.fs)
        """After submission this Dictionary will contain either the
        validated data on successfull validation or the origin submitted
        data."""
        self.validated = False
        """Flag to indicate if the form has been validated. Init value
        is False.  which means no validation has been done."""
        self.external_validators = []
        """List with external validators. Will be called an form validation."""
        self.current_page = 0
        """Number of the currently selected page"""
        self.change_page_callback = change_page_callback
        """Dictionary with some parameters used to call an URL when the
        user changes the currently selected page. The dictionary has the
        following keys:
         * url: Name of the URL which will be called
         * item (optional): A string which is send to the URL as GET
           paramenter. Often this is the name of the element (clazzname)
         * itemid (optional): The id of the currently editied element.
        The url will have the additional parameter "page" which holds
        the currently selected page.
        """
        self.external_renderers = renderers
        """Dictionary with external provided custom renderers."""
        self.fields = self._build_fields()
        """Dictionary with fields."""

    def _build_fields(self):
        """Returns a dictionary with all Field instanced which are
        configured for this form.
        :returns: Dictionary with Field instances

        """
        fields = {}
        for name, field in self._config.get_fields().iteritems():
            fa_field = self.fs[name]
            fields[name] = Field(self, field, fa_field, self._translate)
        return fields

    def has_errors(self):
        """Returns True if one of the fields in the form has errors"""
        for field in self.fields.values():
            if len(field.get_errors()) > 0:
                return True
        return False

    def get_errors(self):
        """Returns a dictionary of all errors in the form.  This
        dictionary will contain the errors if the validation fails. The
        key of the dictionary is the fieldname of the field.  As a field
        can have more than one error the value is a list."""
        errors = {}
        for field in self.fields.values():
            if len(field.get_errors()) > 0:
                errors[field.name] = field.get_errors()
        return errors

    def get_field(self, name):
        return self.fields[name]

    def add_validator(self, validator):
        return self.external_validators.append(validator)

    def render(self, values={}, page=0):
        """Returns the rendererd form as an HTML string.

        :values: Dictionary with values to be prefilled/overwritten in
        the rendered form.
        :returns: Rendered form.

        """
        self.current_page = page
        renderer = FormRenderer(self, self._translate)
        form = renderer.render(values)
        return htmlfill.render(form, values or self.data)

    def _add_error(self, fieldname, error):
        field = self.get_field(fieldname)
        if isinstance(error, list):
            for err in error:
                field.add_error(err)
        else:
            field.add_error(error)

    def _convert(self, field, value):
        """Returns a converted value depending of the fields datatype

        :field: configuration of the field
        :value: value to be converted
        """
        # Handle missing value. Currently we just return None in case
        # that the provided value is an empty String
        if value == "":
            return None

        dtype = field.type
        if dtype == 'integer':
            try:
                return int(value)
            except ValueError:
                msg = "%s is not a integer value." % value
                self._add_error(field.name, msg)
        elif dtype == 'float':
            try:
                return float(value)
            except ValueError:
                msg = "%s is not a float value." % value
                self._add_error(field.name, msg)
        elif dtype == 'date':
            try:
                #@TODO: Support other dateformats that ISO8601
                y, m, d = value.split('-')
                y = int(y)
                m = int(m)
                d = int(d)
                try:
                    return datetime.date(y, m, d)
                except ValueError, e:
                    msg = "%s is an invalid date (%s)" % (value, e)
                    self._add_error(field.name, msg)
            except:
                msg = "%s is not a valid date format." % value
                self._add_error(field.name, msg)
        return value

    def validate(self, submitted):
        """Returns True if the validation succeeds else False.
        Validation of the data happens in three stages:

        1. Prevalidation. Custom rules that are checked before any
        datatype checks on type conversations are made.
        2. Basic type checks and type conversation. Type checks and type
        conversation is done based on the data type of the field and
        further constraint defined in the database if the form is
        instanciated with an SQLAlchemy mapped item.
        3. Postvalidation. Custom rules that are checked after the type
        conversation was done.

        All errors are stored in the errors dictionary through the
        process of validation. After the validation finished the values
        are stored in the data dictionary. In case there has been errors
        the dictionary will contain the origin submitted data.

        :submitted: Dictionary with submitted values.
        :returns: True or False

        """

        # This dictionary will contain the converted data
        values = {}
        fa_validated = False
        # 1. Iterate over all fields and start the validation.
        log.debug('Submitted values: %s' % submitted)
        for fieldname in submitted.keys():
            try:
                field = self._config.get_field(fieldname)
            except KeyError:
                # @TODO:
                # For 1:1 relations FA modifies the fieldname on
                # rendering to the name of the Foreign Key. This leads
                # to problems on validation when the validation code
                # tries to access a field based on the submitted data
                # and raises a KeyError as there is no field with the
                # name of the FK.
                # In this case we we just add the subbmitted data to the
                # validated data, to make the prefilling work after rendering.
                values[fieldname] = submitted.get(fieldname)
                log.warning('Found field "%s" in submitted data,'
                            ' while validating data for "%s" which is'
                            ' not a configured field'
                            % (fieldname, repr(self._item)))
                continue
            # 3. Prevalidation
            for rule in field.rules:
                if rule.mode != 'pre':
                    continue
                result = rule.evaluate(submitted)
                if not result:
                    self._add_error(fieldname, rule.msg)

            # 4. Basic type conversations, Defaults to String
            # Validation can happen in two variations:
            #
            # 4.1 If item is None (No sqlalchemy mapped item is provided),
            # then convert each field in the Form into its python type.
            #
            # 4.2 If an item was provided, than use the FormAlchemy
            # validation once for the whole fieldset. After validation
            # was done save the data into the internal data dictionary.
            if self._item is None:
                values[fieldname] = self._convert(field, submitted[fieldname])
            else:
                if not fa_validated:
                    self.fs.rebind(self._item, data=submitted)
                    fa_valid = self.fs.validate()
                    fa_validated = True
                    if not fa_valid:
                        # Collect all errors form formalchemy
                        for err_field, err_msg in self.fs.errors.iteritems():
                            self._add_error(err_field.key, err_msg)
                if not fa_valid:
                    values[fieldname] = self.fs[fieldname].raw_value
                else:
                    values[fieldname] = self.fs[fieldname].value

            # 5. Postvalidation
            for rule in field.rules:
                if rule.mode != 'post':
                    continue
                result = rule.evaluate(values)
                if not result:
                    self._add_error(fieldname, rule.msg)

        # 6. Custom validation. User defined external validators.
        for validator in self.external_validators:
            if not validator.check(values):
                self._add_error(validator._field, validator._error)

        # If the form is valid. Save the converted and validated data
        # into the data dictionary. If not, than save the origin
        # submitted data.
        has_errors = self.has_errors()
        if not has_errors:
            self.data = values
        else:
            self.data = submitted
        self.validated = True
        return not has_errors

    def save(self):
        """Will save the validated data back into the item. In case of
        an SQLAlchemy mapped item the data will be stored into the
        database.
        :returns: Item with validated data.

        """
        if not self.validated:
            raise StateError('Saving is not possible without prior validation')
        if self.has_errors():
            raise StateError('Saving is not possible if form has errors')

        # @FIXME: _item is only set when this form is used in connection
        # with an SQLAlchemy mapped item.If the form is used as normal
        # form _item is none. This is not consistent. There seems to be
        # more options to fix this:
        # 1. Raise exception when calling save if there is no _item.
        # 2. Make sure there is always an item
        # 3. Save the item if there is an item, else ignore. Return None
        # in both cases.
        if self._item is not None:
            try:
                self._save()
            except:
                self.fs.sync()
            return self._item

    def _save(self):
        mapper = sa.orm.object_mapper(self._item)
        relation_properties = filter(
            lambda p: isinstance(p, sa.orm.properties.RelationshipProperty),
            mapper.iterate_properties)

        relation_names = {}
        for prop in relation_properties:
            relation_names[prop.key] = prop

        #related_classes = [prop.mapper.class_ for prop in relation_properties]
        #related_tables = [prop.target for prop in relation_properties]

        for key, value in self.data.iteritems():
            relation = relation_names.get(key)
            if relation:
                log.info('Todo: Implement setting relation')
                li = self._load_relations(relation.mapper.class_, value)
                try:
                    setattr(self._item, key, li)
                except:
                    log.exception('Error while setting %s with %s' % (key, li))
            else:
                setattr(self._item, key, value)

        self._dbsession.add(self._item)

    def _load_relations(self, relation, values):
        loaded = []
        for value in values:
            db = self._dbsession
            r = db.query(relation).filter(relation.id == value).one()
            loaded.append(r)
        return loaded


class Field(object):
    """Wrapper for fields in the form. The purpose of this class is to
    provide a common interface for the renderer independent to the
    underlying implementation detail of the field."""

    def __init__(self, form, config, fa_field, translate):
        """Initialize the field with the given field configuration.

        :config: Field configuration

        """
        self._form = form
        self._config = config
        self._fa_field = fa_field
        self._translate = translate
        self.renderer = get_renderer(self, translate)
        self._errors = []

    def __getattr__(self, name):
        """Make attributes from the configuration directly available"""
        return getattr(self._config, name)

    def get_value(self, default=None):
        value = self._fa_field.raw_value
        if value:
            return value
        else:
            return default

    def get_options(self):
        user_defined_options = self._config.options
        if user_defined_options:
            return user_defined_options
        elif self._form._dbsession:
            # Get mapped clazz for the field
            options = []
            mapper = sa.orm.object_mapper(self._form._item)
            for prop in mapper.iterate_properties:
                if prop.key == self.name:
                    clazz = prop.mapper.class_
                    items = self._form._dbsession.query(clazz)
                    options = [(item.id, item) for item in items]
                    break
        else:
            # TODO: Try to get the session from the item. Ther must be
            # somewhere the already bound session. (torsten) <2013-07-23 00:27>
            log.warning('No db connection configured for this form. Can '
                        'not load options')
        return options

    def add_error(self, error):
        self._errors.append(error)

    def get_errors(self):
        return self._errors

    def render(self):
        """Returns the rendererd HTML for the field"""
        return self.renderer.render()

    def is_required(self):
        """Returns true if either the required flag of the field
        configuration is set or the formalchemy field is required."""
        return self.required or self._fa_field.is_required()

    def is_readonly(self):
        """Returns true if either the readonly flag of the field
        configuration is set or the formalchemy field is readonly."""
        return self.readonly or self._fa_field.is_readonly()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.