예제 #1
0
    def test_sharing_class_property(self):
        """ When an unknown attribute has the same name as a property on
        the Form class, the attribute is mistakenly seen as known because
        getattr can retrieve the property, but when property.field_class
        is accessed an error is raised. This tests that the error is not
        raised when skip_unknown_keys is True.
        """
        class MyForm(Form):
            a = BooleanField()

        flatten_json(MyForm, {'data': 13})
예제 #2
0
    def test_sharing_class_property(self):
        """ When an unknown attribute has the same name as a property on
        the Form class, the attribute is mistakenly seen as known because
        getattr can retrieve the property, but when property.field_class
        is accessed an error is raised. This tests that the error is not
        raised when skip_unknown_keys is True.
        """
        class MyForm(Form):
            a = BooleanField()

        flatten_json(MyForm, {'data': 13})
예제 #3
0
    def test_sharing_class_property_without_skip_unknown_keys(self):
        """ When an unknown attribute has the same name as a property on
        the Form class, the attribute is mistakenly seen as known because
        getattr can retrieve the property, but when property.field_class
        is accessed an error is raised. This tests that the error IS
        raised when skip_unknown_keys is False.
        """
        class MyForm(Form):
            a = BooleanField()

        with raises(InvalidData):
            flatten_json(MyForm, {'data': 123}, skip_unknown_keys=False)
예제 #4
0
    def test_sharing_class_property_without_skip_unknown_keys(self):
        """ When an unknown attribute has the same name as a property on
        the Form class, the attribute is mistakenly seen as known because
        getattr can retrieve the property, but when property.field_class
        is accessed an error is raised. This tests that the error IS
        raised when skip_unknown_keys is False.
        """
        class MyForm(Form):
            a = BooleanField()

        with raises(InvalidData):
            flatten_json(MyForm, {'data': 123}, skip_unknown_keys=False)
예제 #5
0
    def from_json(cls,
                  formdata=None,
                  obj=None,
                  prefix='',
                  data=None,
                  meta=None,
                  skip_unknown_keys=True,
                  **kwargs):

        # Fix -----------------------
        form_temp = formdata.copy()
        for key in form_temp.keys():
            if not formdata[key] or formdata[key] == [0]:
                del formdata[key]
        # ---------------------------

        form = cls(formdata=MultiDict(
            wtforms_json.flatten_json(
                cls, formdata, skip_unknown_keys=skip_unknown_keys))
                   if formdata else None,
                   obj=obj,
                   prefix=prefix,
                   data=data,
                   meta=meta,
                   **kwargs)
        return form
예제 #6
0
    def test_only_flatten_on_form_field(self):
        class DictField(Field):
            def process_formdata(self, valuelist):
                if valuelist:
                    data = valuelist[0]
                    if isinstance(data, dict):
                        self.data = data
                    else:
                        raise 'Unsupported datatype'
                else:
                    self.data = {}

        class MyForm(Form):
            a = IntegerField()
            b = DictField()

        assert (flatten_json(MyForm, {
            'a': False,
            'b': {
                'key': 'value'
            }
        }) == {
            'a': False,
            'b': {
                'key': 'value'
            }
        })
예제 #7
0
    def test_flatten_nested_listfield_and_formfield_inheritance(self):
        class NestedForm(Form):
            b = TextField()

        class SpecialNestedField(FormField):
            def __init__(self, *args, **kwargs):
                super(SpecialNestedField, self).__init__(
                    NestedForm,
                    *args,
                    **kwargs
                )

        class SpecialField(FieldList):
            def __init__(self, *args, **kwargs):
                super(SpecialField, self).__init__(
                    SpecialNestedField(),
                    *args,
                    **kwargs
                )

        class MyForm(Form):
            a = SpecialField()

        assert flatten_json(MyForm, {'a': [{'b': 1}, {'b': 2}, {'b': 3}]}) == {
            'a-0-b': 1,
            'a-1-b': 2,
            'a-2-b': 3
        }
예제 #8
0
파일: form.py 프로젝트: nanlong/flask_zeus
    def __init__(self, formdata=_Auto, *args, **kwargs):
        kwargs['csrf_enabled'] = False

        if formdata is _Auto and self.is_submitted() and request.json:
            formdata = flatten_json(self.__class__, request.json)
            formdata = werkzeug.datastructures.MultiDict(formdata)

        super(Form, self).__init__(formdata, *args, **kwargs)
예제 #9
0
    def test_supports_dicts(self):
        class MyForm(Form):
            a = BooleanField()
            b = IntegerField()

        assert (
            flatten_json(MyForm, {'a': False, 'b': 123}) ==
            {'a': False, 'b': 123}
        )
예제 #10
0
    def test_supports_dicts(self):
        class MyForm(Form):
            a = BooleanField()
            b = IntegerField()

        assert (
            flatten_json(MyForm, {'a': False, 'b': 123}) ==
            {'a': False, 'b': 123}
        )
예제 #11
0
    def test_supports_nested_dicts_and_lists(self):
        class OtherForm(Form):
            b = BooleanField()

        class MyForm(Form):
            a = FieldList(FormField(OtherForm))

        data = {'a': [{'b': True}]}
        assert flatten_json(MyForm, data) == {'a-0-b': True}
예제 #12
0
    def test_supports_field_list_decoding(self):
        class MyForm(Form):
            a = FieldList(TextField())

        assert flatten_json(MyForm, {'a': [1, 2, 3]}) == {
            'a-0': 1,
            'a-1': 2,
            'a-2': 3
        }
예제 #13
0
    def test_supports_field_list_decoding(self):
        class MyForm(Form):
            a = FieldList(TextField())

        assert flatten_json(MyForm, {'a': [1, 2, 3]}) == {
            'a-0': 1,
            'a-1': 2,
            'a-2': 3
        }
예제 #14
0
    def test_supports_nested_dicts_and_lists(self):
        class OtherForm(Form):
            b = BooleanField()

        class MyForm(Form):
            a = FieldList(FormField(OtherForm))
        data = {
            'a': [{'b': True}]
        }
        assert flatten_json(MyForm, data) == {'a-0-b': True}
예제 #15
0
    def test_flatten_dict(self):
        class DeeplyNestedForm(Form):
            c = StringField()

        class NestedForm(Form):
            b = FormField(DeeplyNestedForm)

        class MyForm(Form):
            a = FormField(NestedForm)

        assert flatten_json(MyForm, {'a': {'b': {'c': 'd'}}}) == {'a-b-c': 'd'}
예제 #16
0
    def test_flatten_formfield_inheritance(self):
        class NestedForm(Form):
            b = StringField()

        class SpecialField(FormField):
            def __init__(self, *args, **kwargs):
                super(SpecialField, self).__init__(NestedForm, *args, **kwargs)

        class MyForm(Form):
            a = SpecialField()

        assert flatten_json(MyForm, {'a': {'b': 'c'}}) == {'a-b': 'c'}
예제 #17
0
    def test_flatten_dict(self):
        class DeeplyNestedForm(Form):
            c = TextField()

        class NestedForm(Form):
            b = FormField(DeeplyNestedForm)

        class MyForm(Form):
            a = FormField(NestedForm)

        assert flatten_json(MyForm, {'a': {'b': {'c': 'd'}}}) == {
            'a-b-c': 'd'
        }
예제 #18
0
    def test_flatten_formfield_inheritance(self):
        class NestedForm(Form):
            b = TextField()

        class SpecialField(FormField):
            def __init__(self, *args, **kwargs):
                super(SpecialField, self).__init__(NestedForm, *args, **kwargs)

        class MyForm(Form):
            a = SpecialField()

        assert flatten_json(MyForm, {'a': {'b': 'c'}}) == {
            'a-b': 'c'
        }
예제 #19
0
    def test_flatten_listfield_inheritance(self):
        class SpecialField(FieldList):
            def __init__(self, *args, **kwargs):
                super(SpecialField, self).__init__(StringField(), *args,
                                                   **kwargs)

        class MyForm(Form):
            a = SpecialField()

        assert flatten_json(MyForm, {'a': [1, 2, 3]}) == {
            'a-0': 1,
            'a-1': 2,
            'a-2': 3
        }
예제 #20
0
    def test_flatten_listfield_inheritance(self):
        class SpecialField(FieldList):
            def __init__(self, *args, **kwargs):
                super(SpecialField, self).__init__(
                    TextField(),
                    *args,
                    **kwargs
                )

        class MyForm(Form):
            a = SpecialField()

        assert flatten_json(MyForm, {'a': [1, 2, 3]}) == {
            'a-0': 1,
            'a-1': 2,
            'a-2': 3
        }
    def process(self, request, container, fallback=None):
        from wtforms_json import MultiDict, flatten_json

        if inspect.isclass(container):
            container = container()

        if request.content_type == 'application/json':
            request_data = MultiDict(flatten_json(container.__class__, parse_json(request.body)))
        else:
            request_data = request.params

        container.process(formdata=request_data, obj=fallback, **container.data)

        self.container = container
        self.fallback = fallback

        return self
예제 #22
0
    def process(self, request, container, fallback=None):
        from wtforms_json import MultiDict, flatten_json

        if inspect.isclass(container):
            container = container()

        if request.content_type == 'application/json':
            request_data = MultiDict(
                flatten_json(container.__class__, parse_json(request.body)))
        else:
            request_data = request.params

        container.process(formdata=request_data,
                          obj=fallback,
                          **container.data)

        self.container = container
        self.fallback = fallback

        return self
예제 #23
0
    def test_only_flatten_on_form_field(self):
        class DictField(Field):
            def process_formdata(self, valuelist):
                if valuelist:
                    data = valuelist[0]
                    if isinstance(data, dict):
                        self.data = data
                    else:
                        raise 'Unsupported datatype'
                else:
                    self.data = {}

        class MyForm(Form):
            a = IntegerField()
            b = DictField()

        assert (
            flatten_json(MyForm, {'a': False, 'b': {'key': 'value'}}) ==
            {'a': False, 'b': {'key': 'value'}}
        )
예제 #24
0
    def _add_entry(self, formdata=None, data=unset_value, index=None):
        '''
        Fill the form with previous data if necessary to handle partial update
        '''
        if formdata:
            prefix = '-'.join((self.name, str(index)))
            basekey = '-'.join((prefix, '{0}'))
            idkey = basekey.format('id')
            if prefix in formdata:
                formdata[idkey] = formdata.pop(prefix)
            if hasattr(self.nested_model, 'id') and idkey in formdata:
                id = self.nested_model.id.to_python(formdata[idkey])
                data = get_by(self.initial_data, 'id', id)

                initial = flatten_json(self.nested_form, data.to_mongo(),
                                       prefix)

                for key, value in initial.items():
                    if key not in formdata:
                        formdata[key] = value
            else:
                data = None
        return super(NestedModelList, self)._add_entry(formdata, data, index)
예제 #25
0
    def _add_entry(self, formdata=None, data=unset_value, index=None):
        '''
        Fill the form with previous data if necessary to handle partial update
        '''
        if formdata:
            prefix = '-'.join((self.name, str(index)))
            basekey = '-'.join((prefix, '{0}'))
            idkey = basekey.format('id')
            if prefix in formdata:
                formdata[idkey] = formdata.pop(prefix)
            if hasattr(self.nested_model, 'id') and idkey in formdata:
                id = self.nested_model.id.to_python(formdata[idkey])
                data = get_by(self.initial_data, 'id', id)

                initial = flatten_json(self.nested_form,
                                       data.to_mongo(),
                                       prefix)

                for key, value in initial.items():
                    if key not in formdata:
                        formdata[key] = value
            else:
                data = None
        return super(NestedModelList, self)._add_entry(formdata, data, index)
예제 #26
0
    def test_unknown_attribute_without_skip_unknown_keys(self):
        class MyForm(Form):
            a = BooleanField()

        with raises(InvalidData):
            flatten_json(MyForm, {'b': 123}, skip_unknown_keys=False)
예제 #27
0
    def test_supports_select_multiple_field_decoding(self):
        class MyForm(Form):
            a = SelectMultipleField()

        assert flatten_json(MyForm, {'a': [1, 2, 3]}) == {'a': [1, 2, 3]}
예제 #28
0
    def test_unknown_attribute(self):
        class MyForm(Form):
            a = BooleanField()

        flatten_json(MyForm, {'b': 123})
예제 #29
0
    def test_unknown_attribute(self):
        class MyForm(Form):
            a = BooleanField()

        with raises(InvalidData):
            flatten_json(MyForm, {'b': 123})
예제 #30
0
 def test_supports_dicts(self):
     assert flatten_json({'a': False, 'b': 123}) == {'a': False, 'b': 123}
예제 #31
0
    def test_supports_select_multiple_field_decoding(self):
        class MyForm(Form):
            a = SelectMultipleField()

        assert flatten_json(MyForm, {'a': [1, 2, 3]}) == {'a': [1, 2, 3]}
예제 #32
0
 def test_raises_error_if_given_data_not_dict_like(self):
     class MyForm(Form):
         pass
     with raises(InvalidData):
         flatten_json(MyForm, [])
예제 #33
0
 def test_supports_dicts_with_lists(self):
     assert flatten_json({'a': [1, 2, 3]}) == {'a-0': 1, 'a-1': 2, 'a-2': 3}
예제 #34
0
    def test_unknown_attribute(self):
        class MyForm(Form):
            a = BooleanField()

        flatten_json(MyForm, {'b': 123})
예제 #35
0
    def test_unknown_attribute_without_skip_unknown_keys(self):
        class MyForm(Form):
            a = BooleanField()

        with raises(InvalidData):
            flatten_json(MyForm, {'b': 123}, skip_unknown_keys=False)
예제 #36
0
 def test_raises_error_if_given_data_not_dict_like(self):
     class MyForm(Form):
         pass
     with raises(InvalidData):
         flatten_json(MyForm, [])
예제 #37
0
 def test_supports_nested_dicts_and_lists(self):
     data = {
         'a': [{'b': True}]
     }
     assert flatten_json(data) == {'a-0-b': True}
예제 #38
0
 def __init__(self, **kwargs):
     formdata = Context.request.get_json()
     if formdata is not None:
         formdata = MultiDict(flatten_json(self.__class__, formdata))
     super().__init__(formdata, **kwargs)
예제 #39
0
 def test_flatten_dict(self):
     assert flatten_json({'a': {'b': {'c': 'd'}}}) == {'a-b-c': 'd'}
예제 #40
0
 def test_supports_empty_lists(self):
     data = {
         'a': []
     }
     assert flatten_json(data) == {}
예제 #41
0
 def wrap_formdata(self, form, formdata):
     if formdata is _Auto:
         if _is_submitted():
             return ImmutableMultiDict(wtforms_json.flatten_json(form.__class__, request.get_json()))
     return super().wrap_formdata(form, formdata)
예제 #42
0
 def test_raises_error_if_given_data_not_dict_like(self):
     with raises(InvalidData):
         flatten_json([])