Ejemplo n.º 1
0
    def _multipart_value(self, config):
        is_file = lambda value: 'filename' in value
        file_fields = [(name, value) for name, value in self._value.items()
                       if is_file(value)]
        form_fields = [(name, value) for name, value in self._value.items()
                       if not is_file(value)]

        if self._lookup_var:
            load_variable = lambda n, v: config.load_variable(n, v)
        else:
            load_variable = lambda n, v: v

        fields = {}
        for name, data in form_fields:
            value = load_variable(name, data['value'])
            charset = data.get('charset', 'UTF-8')
            if isinstance(value, six.text_type):
                value = value.encode(charset)

            content_type = '{0}; charset={1}'.format(
                data['Content-Type'], charset)

            fields[name] = ('', BytesIO(value), content_type)

        with ExitStack() as stack:
            for name, data in file_fields:
                file_path = get_file_path(
                    data['filename'], config.test_filename)
                fh = stack.enter_context(open(file_path, 'rb'))
                fields[name] = fh
            yield {'files': fields}
Ejemplo n.º 2
0
 def load(self, filename, variables):
     if not self._is_loaded:
         file_path = get_file_path(self._filename, filename)
         try:
             with open(file_path) as fh:
                 data = fh.read()
         except Exception as exc:
             raise InvalidVariable(
                 'Unable to read file {0!r}: {1!r}'.format(
                     file_path, str(exc)))
         if self._strip:
             data = data.strip()
         value = self._format_handlers[self._format](data)
         self._value = value
         self._is_loaded = True
     return self._is_loaded