我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用django.utils.datastructures.MultiValueDict()。
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
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])
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
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'])
def value_from_datadict(self, data, files, name): if isinstance(data, MultiValueDict): return data.getlist(name) return data.get(name)
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()
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.META.get('CONTENT_TYPE', '').startswith('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.META.get('CONTENT_TYPE', '').startswith('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()
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)
def get_cleansed_multivaluedict(self, request, multivaluedict): """ Replaces the keys in a MultiValueDict marked as sensitive with stars. This mitigates leaking sensitive POST parameters if something like request.POST['nonexistent_key'] throws an exception (#21098). """ sensitive_post_parameters = getattr(request, 'sensitive_post_parameters', []) if self.is_active(request) and sensitive_post_parameters: multivaluedict = multivaluedict.copy() for param in sensitive_post_parameters: if param in multivaluedict: multivaluedict[param] = CLEANSED_SUBSTITUTE return multivaluedict
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
def value_from_datadict(self, data, files, name): # Accept `sfields` to be a comma-separated string of fields (#46) if "," in data.get(name, ""): return data.get(name).split(u',') if isinstance(data, MultiValueDict): return data.getlist(name) return data.get(name, None)
def post_data(**kwargs): for key, value in kwargs.items(): if isinstance(value, str): kwargs[key] = [value] return MultiValueDict(kwargs)
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
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)
def get_step_data(self, step): # When reading the serialized data, upconvert it to a MultiValueDict, # some serializers (json) don't preserve the type of the object. values = self.data[self.step_data_key].get(step, None) if values is not None: values = MultiValueDict(values) return values
def set_step_data(self, step, cleaned_data): # If the value is a MultiValueDict, convert it to a regular dict of the # underlying contents. Some serializers call the public API on it (as # opposed to the underlying dict methods), in which case the content # can be truncated (__getitem__ returns only the first item). if isinstance(cleaned_data, MultiValueDict): cleaned_data = dict(cleaned_data.lists()) self.data[self.step_data_key][step] = cleaned_data
def value_from_datadict(self, data, files, name): if isinstance(files, MultiValueDict): return files.getlist(name) else: return files.get(name)
def value_from_datadict(self, data, files, name): if isinstance(data, (MultiValueDict, MergeDict)): return data.getlist(name) return data.get(name, None)
def _parse(self): """ Parse the request content, returning a two-tuple of (data, files) May raise an `UnsupportedMediaType`, or `ParseError` exception. """ stream = self.stream media_type = self.content_type if stream is None or media_type is None: empty_data = QueryDict('', encoding=self._request._encoding) empty_files = MultiValueDict() return (empty_data, empty_files) parser = self.negotiator.select_parser(self, self.parsers) if not parser: raise exceptions.UnsupportedMediaType(media_type) try: parsed = parser.parse(stream, media_type, self.parser_context) except: # If we get an exception during parsing, fill in empty data and # re-raise. Ensures we don't simply repeat the error when # attempting to render the browsable renderer response, or when # logging the request or similar. self._data = QueryDict('', encoding=self._request._encoding) self._files = MultiValueDict() self._full_data = self._data raise # Parser classes may return the raw data, or a # DataAndFiles object. Unpack the result as required. try: return (parsed.data, parsed.files) except AttributeError: empty_files = MultiValueDict() return (parsed, empty_files)
def value_from_datadict(self, data, files, name): from django.utils.datastructures import MultiValueDict if isinstance(data, MultiValueDict): # Normally, we'd want a list here, which is what we get from the # SelectMultiple superclass, but the SimpleArrayField expects to # get a delimited string, so we're doing a little extra work. return self.delimiter.join(data.getlist(name)) return data.get(name, None)