Python django.utils.datastructures.MultiValueDict() Examples

The following are 30 code examples of django.utils.datastructures.MultiValueDict(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.datastructures , or try the search function .
Example #1
Source File: forms.py    From mrs with GNU Affero General Public License v3.0 6 votes vote down vote up
def args_extract(self, args, kwargs):
        """Extract data and files args, return mutable objects."""
        # make popable (can't pop tuple of args)
        args = list(args)

        def getarg(name, num):
            if args and len(args) > num:
                return args.pop(num)
            elif kwargs.get('files'):
                return kwargs.pop('files')
            return None

        # First to not affect data = args.pop(0)
        files = getarg('files', 1)
        data = getarg('data', 0)

        # make mutable if something
        if files:
            files = MultiValueDict(files)
        if data:
            data = MultiValueDict(data)

        return data, files, args, kwargs 
Example #2
Source File: request.py    From bioforum with MIT License 6 votes vote down vote up
def __init__(self):
        # WARNING: The `WSGIRequest` subclass doesn't call `super`.
        # Any variable assignment made here should also happen in
        # `WSGIRequest.__init__()`.

        self.GET = QueryDict(mutable=True)
        self.POST = QueryDict(mutable=True)
        self.COOKIES = {}
        self.META = {}
        self.FILES = MultiValueDict()

        self.path = ''
        self.path_info = ''
        self.method = None
        self.resolver_match = None
        self._post_parse_error = False
        self.content_type = None
        self.content_params = None 
Example #3
Source File: request.py    From python with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        # WARNING: The `WSGIRequest` subclass doesn't call `super`.
        # Any variable assignment made here should also happen in
        # `WSGIRequest.__init__()`.

        self.GET = QueryDict(mutable=True)
        self.POST = QueryDict(mutable=True)
        self.COOKIES = {}
        self.META = {}
        self.FILES = MultiValueDict()

        self.path = ''
        self.path_info = ''
        self.method = None
        self.resolver_match = None
        self._post_parse_error = False
        self.content_type = None
        self.content_params = None 
Example #4
Source File: request.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def __init__(self):
        # WARNING: The `WSGIRequest` subclass doesn't call `super`.
        # Any variable assignment made here should also happen in
        # `WSGIRequest.__init__()`.

        self.GET = QueryDict(mutable=True)
        self.POST = QueryDict(mutable=True)
        self.COOKIES = {}
        self.META = {}
        self.FILES = MultiValueDict()

        self.path = ''
        self.path_info = ''
        self.method = None
        self.resolver_match = None
        self._post_parse_error = False
        self.content_type = None
        self.content_params = None 
Example #5
Source File: request.py    From python2017 with MIT License 6 votes vote down vote up
def __init__(self):
        # WARNING: The `WSGIRequest` subclass doesn't call `super`.
        # Any variable assignment made here should also happen in
        # `WSGIRequest.__init__()`.

        self.GET = QueryDict(mutable=True)
        self.POST = QueryDict(mutable=True)
        self.COOKIES = {}
        self.META = {}
        self.FILES = MultiValueDict()

        self.path = ''
        self.path_info = ''
        self.method = None
        self.resolver_match = None
        self._post_parse_error = False
        self.content_type = None
        self.content_params = None 
Example #6
Source File: fields.py    From drf-mongo-filters with GNU General Public License v2.0 6 votes vote down vote up
def get_value(self, data):
        if isinstance(data, MultiValueDict):
            regex = re.compile(r"^%s\.(.*)$" % re.escape(self.field_name))
            ret = {}
            for name, value in data.items():
                match = regex.match(name)
                if not match:
                    continue
                key = match.groups()[0]
                if value != '':
                    ret[key] = value
        elif isinstance(data, dict):
            ret = data.get(self.field_name, fields.empty)
        else:
            raise ValidationError("not a dict: " + str(type(data)))

        if ret is fields.empty or len(ret) == 0:
            return fields.empty
        return ret 
Example #7
Source File: test_field_types.py    From intake with MIT License 6 votes vote down vote up
def test_parses_empty_multivalue_dicts(self):
        empty = MultiValueDict({
            'dob.year': [],
            'dob.day': [],
            'dob.month': [],
        })
        blank = MultiValueDict({
            'dob.year': [''],
            'dob.day': [''],
            'dob.month': [''],
        })
        missing = MultiValueDict({})
        for input_data in [empty, blank, missing]:
            field = fields.DateOfBirthField(input_data, required=False)
            self.assertParsesCorrectly(
                field, self.empty_value, [None, None, None]) 
Example #8
Source File: team_id_api_test.py    From rankedftw with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_4v4(self):
        p1 = self.db.create_player(region=Region.EU, realm=1, bid=301)
        p2 = self.db.create_player(region=Region.EU, realm=1, bid=302)
        p3 = self.db.create_player(region=Region.EU, realm=1, bid=303)
        p4 = self.db.create_player(region=Region.EU, realm=1, bid=304)
        t = self.db.create_team(mode=Mode.TEAM_4V4, member0=p1, member1=p2, member2=p3, member3=p4)

        qp = MultiValueDict()
        qp.setlist('player',
                   [
                       'http://eu.battle.net/sc2/en/profile/304/1/xyz',
                       'http://eu.battle.net/sc2/en/profile/303/1/xyz',
                       'http://eu.battle.net/sc2/en/profile/302/1/xyz',
                       'http://eu.battle.net/sc2/en/profile/301/1/xyz',
                   ])
        qp['mode'] = 'team-4v4'
        response = self.c.get('/team/id/', qp)

        self.assertEqual(200, response.status_code)
        data = json.loads(response.content.decode('utf-8'))
        self.assertEqual(t.id, data['team_id']) 
Example #9
Source File: request.py    From python2017 with MIT License 5 votes vote down vote up
def parse_file_upload(self, META, post_data):
        """Returns a tuple of (POST QueryDict, FILES MultiValueDict)."""
        self.upload_handlers = ImmutableList(
            self.upload_handlers,
            warning="You cannot alter upload handlers after the upload has been processed."
        )
        parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
        return parser.parse() 
Example #10
Source File: request.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def parse_file_upload(self, META, post_data):
        """Returns a tuple of (POST QueryDict, FILES MultiValueDict)."""
        self.upload_handlers = ImmutableList(
            self.upload_handlers,
            warning="You cannot alter upload handlers after the upload has been processed."
        )
        parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
        return parser.parse() 
Example #11
Source File: request.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def _mark_post_parse_error(self):
        self._post = QueryDict('')
        self._files = MultiValueDict()
        self._post_parse_error = True 
Example #12
Source File: tests.py    From product-definition-center with MIT License 5 votes vote down vote up
def test_fields_from_context(self):
        param_dict = {'fields': ['a', 'b'], 'exclude_fields': []}
        self.mock_request.query_params = MultiValueDict(param_dict)
        serializer = self.serializer(context=self.context)
        self.assertEqual(['a', 'b'], serializer.fields.keys()) 
Example #13
Source File: debug.py    From python2017 with MIT License 5 votes vote down vote up
def cleanse_special_types(self, request, value):
        try:
            # If value is lazy or a complex object of another kind, this check
            # might raise an exception. isinstance checks that lazy
            # MultiValueDicts will have a return value.
            is_multivalue_dict = isinstance(value, MultiValueDict)
        except Exception as e:
            return '{!r} while evaluating {!r}'.format(e, value)

        if is_multivalue_dict:
            # Cleanse MultiValueDicts (request.POST is the one we usually care about)
            value = self.get_cleansed_multivaluedict(request, value)
        return value 
Example #14
Source File: http.py    From python2017 with MIT License 5 votes vote down vote up
def urlencode(query, doseq=0):
    """
    A version of Python's urllib.urlencode() function that can operate on
    unicode strings. The parameters are first cast to UTF-8 encoded strings and
    then encoded as per normal.
    """
    if isinstance(query, MultiValueDict):
        query = query.lists()
    elif hasattr(query, 'items'):
        query = query.items()
    return original_urlencode(
        [(force_str(k),
         [force_str(i) for i in v] if isinstance(v, (list, tuple)) else force_str(v))
            for k, v in query],
        doseq) 
Example #15
Source File: mock.py    From intake with MIT License 5 votes vote down vote up
def get_multivalue_examples(key, options):
    single = MultiValueDict({
        key: options[-1:]})
    multi = MultiValueDict({
        key: options})
    empty = MultiValueDict({
        key: []})
    blank = MultiValueDict({
        key: ['']})
    missing = MultiValueDict({})
    return single, multi, empty, blank, missing 
Example #16
Source File: request.py    From python2017 with MIT License 5 votes vote down vote up
def _load_post_and_files(self):
        """Populate self._post and self._files if the content-type is a form type"""
        if self.method != 'POST':
            self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
            return
        if self._read_started and not hasattr(self, '_body'):
            self._mark_post_parse_error()
            return

        if self.content_type == 'multipart/form-data':
            if hasattr(self, '_body'):
                # Use already read data
                data = BytesIO(self._body)
            else:
                data = self
            try:
                self._post, self._files = self.parse_file_upload(self.META, data)
            except MultiPartParserError:
                # An error occurred while parsing POST data. Since when
                # formatting the error the request handler might access
                # self.POST, set self._post and self._file to prevent
                # attempts to parse POST data again.
                # Mark that an error occurred. This allows self.__repr__ to
                # be explicit about it instead of simply representing an
                # empty POST
                self._mark_post_parse_error()
                raise
        elif self.content_type == 'application/x-www-form-urlencoded':
            self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
        else:
            self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict() 
Example #17
Source File: tests.py    From product-definition-center with MIT License 5 votes vote down vote up
def test_exclude_fields_from_context(self):
        param_dict = {'fields': [], 'exclude_fields': ['b']}
        self.mock_request.query_params = MultiValueDict(param_dict)
        serializer = self.serializer(context=self.context)
        self.assertEqual(['a', 'c'], serializer.fields.keys()) 
Example #18
Source File: base.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def config_to_form(self, data: Dict[str, Any], points: Decimal) -> Dict[str, Any]:
        """
        Convert a QuestionVersion.config value back to a corresponding request.POST style dict, so we can validate
        JSON imports using existing for validators.

        Will likely need to override this if .ConfigForm has validators that change the data as part of the cleaning.
        """
        text = data['text']
        formdata = MultiValueDict({k: [v] for k,v in data.items() if k != 'text'})
        formdata['text_0'] = text[0]
        formdata['text_1'] = text[1]
        formdata['text_2'] = text[2]
        formdata['points'] = points
        return formdata 
Example #19
Source File: tests.py    From product-definition-center with MIT License 5 votes vote down vote up
def test_exclude_bad_fields_from_context(self):
        param_dict = {'fields': [], 'exclude_fields': ['b', 'd']}
        self.mock_request.query_params = MultiValueDict(param_dict)
        self.assertRaises(FieldError, self.serializer, context=self.context) 
Example #20
Source File: http.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def urlencode(query, doseq=0):
    """
    A version of Python's urllib.urlencode() function that can operate on
    unicode strings. The parameters are first case to UTF-8 encoded strings and
    then encoded as per normal.
    """
    if isinstance(query, MultiValueDict):
        query = query.lists()
    elif hasattr(query, 'items'):
        query = query.items()
    return urllib_parse.urlencode(
        [(force_str(k),
         [force_str(i) for i in v] if isinstance(v, (list,tuple)) else force_str(v))
            for k, v in query],
        doseq) 
Example #21
Source File: widgets.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def value_from_datadict(self, data, files, name):
        if isinstance(data, (MultiValueDict, MergeDict)):
            return data.getlist(name)
        return data.get(name, None) 
Example #22
Source File: widgets.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def value_from_datadict(self, data, files, name):
        if isinstance(data, (MultiValueDict, MergeDict)):
            return data.getlist(name)
        return data.get(name, None) 
Example #23
Source File: compat_tests.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_multivalue_dict():
    d = MultiValueDict()
    d.update({"a": "b", "b": "d"})
    d.update({"a": "c", "e": "f"})
    d = compat.multidict_to_dict(d)
    assert d == {"a": ["b", "c"], "b": "d", "e": "f"} 
Example #24
Source File: mock.py    From intake with MIT License 5 votes vote down vote up
def post_data(**kwargs):
    for key, value in kwargs.items():
        if isinstance(value, str):
            kwargs[key] = [value]
    return MultiValueDict(kwargs) 
Example #25
Source File: test_field_types.py    From intake with MIT License 5 votes vote down vote up
def test_parses_filled_multivalue_dicts(self):
        single = MultiValueDict({
            'dob.year': ['1982'],
            'dob.day': ['2'],
            'dob.month': ['12'],
        })
        multi = MultiValueDict({
            'dob.year': ['2000', '1982'],
            'dob.day': ['5', '2'],
            'dob.month': ['1', '12'],
        })
        for input_data in [single, multi]:
            field = fields.DateOfBirthField(input_data)
            self.assertParsesCorrectly(field, self.parsed_value) 
Example #26
Source File: mock.py    From intake with MIT License 5 votes vote down vote up
def post_data(**kwargs):
    for key, value in kwargs.items():
        if isinstance(value, str):
            kwargs[key] = [value]
    return MultiValueDict(kwargs) 
Example #27
Source File: request.py    From python with Apache License 2.0 5 votes vote down vote up
def _load_post_and_files(self):
        """Populate self._post and self._files if the content-type is a form type"""
        if self.method != 'POST':
            self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
            return
        if self._read_started and not hasattr(self, '_body'):
            self._mark_post_parse_error()
            return

        if self.content_type == 'multipart/form-data':
            if hasattr(self, '_body'):
                # Use already read data
                data = BytesIO(self._body)
            else:
                data = self
            try:
                self._post, self._files = self.parse_file_upload(self.META, data)
            except MultiPartParserError:
                # An error occurred while parsing POST data. Since when
                # formatting the error the request handler might access
                # self.POST, set self._post and self._file to prevent
                # attempts to parse POST data again.
                # Mark that an error occurred. This allows self.__repr__ to
                # be explicit about it instead of simply representing an
                # empty POST
                self._mark_post_parse_error()
                raise
        elif self.content_type == 'application/x-www-form-urlencoded':
            self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
        else:
            self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict() 
Example #28
Source File: request.py    From python with Apache License 2.0 5 votes vote down vote up
def parse_file_upload(self, META, post_data):
        """Returns a tuple of (POST QueryDict, FILES MultiValueDict)."""
        self.upload_handlers = ImmutableList(
            self.upload_handlers,
            warning="You cannot alter upload handlers after the upload has been processed."
        )
        parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
        return parser.parse() 
Example #29
Source File: http.py    From python with Apache License 2.0 5 votes vote down vote up
def urlencode(query, doseq=0):
    """
    A version of Python's urllib.urlencode() function that can operate on
    unicode strings. The parameters are first cast to UTF-8 encoded strings and
    then encoded as per normal.
    """
    if isinstance(query, MultiValueDict):
        query = query.lists()
    elif hasattr(query, 'items'):
        query = query.items()
    return original_urlencode(
        [(force_str(k),
         [force_str(i) for i in v] if isinstance(v, (list, tuple)) else force_str(v))
            for k, v in query],
        doseq) 
Example #30
Source File: debug.py    From python with Apache License 2.0 5 votes vote down vote up
def cleanse_special_types(self, request, value):
        try:
            # If value is lazy or a complex object of another kind, this check
            # might raise an exception. isinstance checks that lazy
            # MultiValueDicts will have a return value.
            is_multivalue_dict = isinstance(value, MultiValueDict)
        except Exception as e:
            return '{!r} while evaluating {!r}'.format(e, value)

        if is_multivalue_dict:
            # Cleanse MultiValueDicts (request.POST is the one we usually care about)
            value = self.get_cleansed_multivaluedict(request, value)
        return value