Exemplo n.º 1
0
 def _load_post_data(self):
     """Method used internally to retrieve submitted data."""
     self._data_stream = _empty_stream
     post = []
     files = []
     if self.environ['REQUEST_METHOD'] in ('POST', 'PUT'):
         storage = _StorageHelper(self.environ, self._get_file_stream)
         if storage.file:
             self._data_stream = storage.file
         if storage.list is not None:
             for key in storage.keys():
                 values = storage[key]
                 if not isinstance(values, list):
                     values = [values]
                 for item in values:
                     if getattr(item, 'filename', None) is not None:
                         fn = item.filename.decode(self.charset, 'ignore')
                         # fix stupid IE bug (IE6 sends the whole path)
                         if fn[1:3] == ':\\':
                             fn = fn.split('\\')[-1]
                         files.append((key, FileStorage(key, fn, item.type,
                                       item.length, item.file)))
                     else:
                         post.append((key, item.value.decode(self.charset,
                                                             'ignore')))
     self._form = MultiDict(post)
     self._files = MultiDict(files)
Exemplo n.º 2
0
def get_widget_output(FieldClass,
                      validators=list(),
                      description='',
                      check=False,
                      process=False,
                      **kwargs):
    """
  Return widget output as **BeautifulSoup** parser.

  Build a form, add an instance of *FieldClass* with the given *validators*
  and return a BeautifulSoup representation of the widgets output.

  If *process* is set (needs to be a ``Dict``), call ``process`` with it.
  If *check* is set, the form gets validated. Finally *kwargs* are
  passed to the call to the widget.

  """
    class TestForm(Form):
        test = FieldClass('Testfield',
                          description=description,
                          validators=validators)

    if not BeautifulSoup:
        raise SkipTest('This test requires `BeautifulSoup`.')
    f = TestForm()
    if process:
        if not MultiDict:
            raise SkipTest('This test requires `Werkzeug`.')
        f.process(MultiDict(process))
    if check:
        f.validate()
    return BeautifulSoup(f.test(**kwargs), 'html.parser').input
Exemplo n.º 3
0
def get_form(form_data={}, flags=[], use_meta=False, **kwargs):
    """
    Returns a WTForms :cls:`Form`.

    The form has one :cls:`StringField` named `test_field` and the *kwargs*
    are used as arguments for the field instance. If *flags* is set, the given
    flags are set for the field too.

    If *form_data* is set, it is cast to a :cls:`Werkzeug.MultiDict` and
    used to fill the form using the :meth:`Form.process` method.

    """
    meta_class = AutoAttrMeta if use_meta else object

    class TestForm(Form):
        class Meta(meta_class):
            pass
        test_field = StringField('Testfield', **kwargs)

    # create instance
    form = TestForm()

    # flags
    for flag in flags:
        setattr(form.test_field.flags, flag, True)

    # process data
    if form_data:
        if MultiDict is None:
            raise SkipTest(
                'This test requires `MultiDict` from `Werkzeug`.'
            )
        form.process(MultiDict(form_data))

    return form
Exemplo n.º 4
0
 def args(self):
     """URL parameters"""
     items = []
     qs = self.environ.get('QUERY_STRING', '')
     for key, values in cgi.parse_qs(qs, True).iteritems():
         for value in values:
             value = value.decode(self.charset, 'ignore')
             items.append((key, value))
     return MultiDict(items)
Exemplo n.º 5
0
def test_request():
    client = Client(request_test_app, RequestTestResponse)

    # get requests
    response = client.get('/?foo=bar&foo=hehe')
    assert response['args'] == MultiDict([('foo', 'bar'), ('foo', 'hehe')])
    assert response['args_as_list'] == [('foo', ['bar', 'hehe'])]
    assert response['form'] == MultiDict()
    assert response['form_as_list'] == []
    assert response['data'] == ''
    assert_request_test_environ(response['environ'], 'GET')

    # post requests with form data
    response = client.post('/?blub=blah', data='foo=blub+hehe&blah=42',
                           content_type='application/x-www-form-urlencoded')
    assert response['args'] == MultiDict([('blub', 'blah')])
    assert response['args_as_list'] == [('blub', ['blah'])]
    assert response['form'] == MultiDict([('foo', 'blub hehe'), ('blah', '42')])
    assert response['data'] == ''
    # currently we do not guarantee that the values are ordered correctly
    # for post data.
    ## assert response['form_as_list'] == [('foo', ['blub hehe']), ('blah', ['42'])]
    assert_request_test_environ(response['environ'], 'POST')

    # post requests with json data
    json = '{"foo": "bar", "blub": "blah"}'
    response = client.post('/?a=b', data=json, content_type='application/json')
    assert response['data'] == json
    assert response['args'] == MultiDict([('a', 'b')])
    assert response['form'] == MultiDict()
def operate_matrix():
    """
    Method to handle POST request to handle matrix manipulation
    :return:
    """
    def _convert_matrix_format(_data):
        """
        Method to convert all list data to required form
        :param _data: dict
        :return: dict
        """
        _result = []
        _matrix = ["matrix_1", "matrix_1_param", "matrix_2", "matrix_2_param"]

        for _m in _matrix:
            # Clean matrix data to required form
            if _data and _data.get(_m):
                _result += _clean_matrix_data(_data.get(_m), _m)

        # Update data
        for _res in _result:
            _data.update({_res[0]: _res[1]})

        # Remove list access
        for _m in _matrix:
            if _data and _data.get(_m):
                del _data[_m]

        return _data

    def _clean_matrix_data(_data, _prefix):
        """
        Method to convert matrix data to required form
        :param _data: List
        :param _prefix: String
        :return: List
        """
        _result = []
        _index = 0

        for _d in _data:
            # Remove None/null data
            if _d:
                _key = "%s-%d" % (_prefix, _index)
                _result.append([_key, _d])
                _index += 1

        return _result

    result = copy.copy(GLOBAL_API_RESPONSE)
    # Fetch form data and convert to dict format
    data = request.get_json()
    # Convert matrix data to required form requirements
    data = _convert_matrix_format(data)
    # Convert json data to form data requirements (MultiDict)
    data = MultiDict(data)

    # Parse data via form
    form = OperationForm(data)

    # Validate form
    if form.validate():
        operation_success = False
        operated_data = None
        operator = form.operator.data

        matrix = MatrixManager(form.matrix_1.data, form.matrix_1_param.data,
                               form.matrix_2.data, form.matrix_2_param.data)

        # Perform requested operations
        if operator == "ADD":
            operation_success, operated_data = matrix.add()
        elif operator == "SUB":
            operation_success, operated_data = matrix.subtract()
        elif operator == "MUL":
            operation_success, operated_data = matrix.multiplication()
        elif operator == "TRA":
            operation_success, operated_data = matrix.transpose()

        # Check if operation successful
        if operation_success:
            result['success'] = True
            result['data'] = {'result': str(operated_data)}
            result['message'] = "Calculations successful"
        else:
            # Operation failed
            result['message'] = operated_data
    else:
        # Handling form errors
        result['data'] = form.errors
        result['message'] = "Validation Errors"

    return jsonify(result)
def test_multidict():
    """Template multidict behavior"""
    t = Template('$a|$b')
    assert t.render(MultiDict(dict(a=[1, 2], b=2))) == '1|2'