本文整理汇总了Python中django.http.request.QueryDict.setlist方法的典型用法代码示例。如果您正苦于以下问题:Python QueryDict.setlist方法的具体用法?Python QueryDict.setlist怎么用?Python QueryDict.setlist使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.http.request.QueryDict
的用法示例。
在下文中一共展示了QueryDict.setlist方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: encode_data
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
def encode_data(data, content_type=None):
# type: (Any, Optional[text_type]) -> Any
# content_type of None means django's test client's default content type
# if content_type is None, return data as it is
if content_type is None:
if data is None:
return {}
else:
return data
elif content_type.startswith('application/json'):
if data is None:
raise BadDataError("empty_json")
try:
return force_text(json.dumps(data, cls=DjangoJSONEncoder))
except ValueError:
raise BadDataError("invalid_format")
elif content_type.startswith(FORM_CONTENT_TYPE):
if data is None or data == "":
return ""
elif isinstance(data, dict):
form_data = QueryDict(mutable=True)
for key, value in six.iteritems(data):
if isinstance(value, Sequence) and not(isinstance(value, text_type)):
form_data.setlist(str(key), value)
else:
form_data[key] = value
return form_data.urlencode()
else:
raise BadDataError("invalid_format")
else:
raise ContentTypeError(content_type)
示例2: dict_to_querydict
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
def dict_to_querydict(dict_data):
qdict = QueryDict('', mutable=True)
for key, value in dict_data.items():
if isinstance(value, list):
qdict.setlist(key, value)
else:
qdict[key] = value
return qdict
示例3: test_county_select_persists_after_session_update
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
def test_county_select_persists_after_session_update(self):
response = self.client.fill_form(
reverse('intake-apply'), counties=['alameda', 'contracosta'],
confirm_county_selection='yes')
request = response.wsgi_request
qdict = QueryDict('', mutable=True)
qdict.setlist('hello', ['world'])
utils.save_form_data_to_session(
request, ApplicantFormViewBase.session_key, qdict)
form_data = self.client.session.get(ApplicantFormViewBase.session_key)
self.assertListEqual(['alameda', 'contracosta'], form_data['counties'])
示例4: get_form_data_from_session
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
def get_form_data_from_session(request, session_key):
"""Gets a dictionary from the session based on a key
and converts each key, list pair into a mutable QueryDict
so that it can be processed by a form as if it were post data
"""
raw_dict = request.session.get(session_key, {})
qdict = QueryDict('', mutable=True)
for key, items in raw_dict.items():
if not isinstance(items, list):
items = [items]
qdict.setlist(key, items)
return qdict
示例5: test_clone_url
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
def test_clone_url(self):
start_host = settings.JWT_COOKIE_CLONE_DOMAINS_ENDPOINT[0]
self.client = Client(SERVER_NAME=start_host, HTTP_HOST=start_host)
# Create a token
params = QueryDict(mutable=True)
params[settings.REDIRECT_URL_VALID_PARAMS[0]] = "http://google.com"
clone_domains = settings.JWT_COOKIE_CLONE_DOMAINS_ENDPOINT
params.setlist('clone-domains', clone_domains)
jwt_token = jwt_utils.create_jwt(self.user)
url_path = reverse('auth:clone-cookie', kwargs={'token': jwt_token})
url = urllib.parse.ParseResult(
scheme="",
netloc="",
path=url_path,
params="",
query=params.urlencode(),
fragment="",
)
resp = self.client.get(url.geturl(), follow=True)
self.assertEqual(200, resp.status_code)
# Check cloning redirects
for k, i in enumerate(resp.redirect_chain[:-1]):
clone_domains = list(settings.JWT_COOKIE_CLONE_DOMAINS_ENDPOINT)
params = QueryDict(mutable=True)
params[settings.REDIRECT_URL_VALID_PARAMS[0]] = "http://google.com"
params.setlist('clone-domains', clone_domains[k+1:])
clone_domains = clone_domains[k:]
if len(clone_domains) > 0:
next_host = clone_domains[0]
else:
next_host = ""
url = urllib.parse.ParseResult(
scheme="http",
netloc=next_host,
path=url_path,
params="",
query=params.urlencode(),
fragment="",
)
# Final redirect (redirect uri)
self.assertEqual(302, resp.redirect_chain[-1][1])
self.assertEqual(params[settings.REDIRECT_URL_VALID_PARAMS[0]],
resp.redirect_chain[-1][0])
示例6: _scrub_GET
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
def _scrub_GET(self,GET):
"""Scrubbs a QueryDict object. This function is subject to change
without notice."""
OUT=QueryDict(mutable=True)
# multilpe 's' get split by white space as well
if 's' in GET:
esses = GET.getlist('s')
s=[]
for ess in esses:
s.extend(ess.strip().split())
if 0 < len(s):
OUT.setlist('s',s)
# anything else is hacking.
return OUT
示例7: get_form
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
def get_form(self):
page = self.get_page()
form_class = page.get_edit_handler().get_form_class(page._meta.model)
parent_page = page.get_parent().specific
if self.session_key not in self.request.session:
# Session key not in session, returning null form
return form_class(instance=page, parent_page=parent_page)
post_data_dict, timestamp = self.request.session[self.session_key]
# convert post_data_dict back into a QueryDict
post_data = QueryDict('', mutable=True)
for k, v in post_data_dict.items():
post_data.setlist(k, v)
return form_class(post_data, instance=page, parent_page=parent_page)
示例8: read_raw_data
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
def read_raw_data(self, request):
# convert the data into the correct format and add
# it as POST variables.
from django.http.request import QueryDict, MultiValueDict
if not request.method in ['POST', 'PUT']:
request._post, request._files = QueryDict('', encoding=request._encoding), MultiValueDict()
else:
# TODO multipart (files) not supported.
q = QueryDict('', encoding=request._encoding).copy()
d = self._raw_data_to_dict(request)
for key in d.keys():
if isinstance(d[key], list):
q.setlist(key, d.pop(key))
q.update(d)
request.method = 'POST'
request._post = q
request._files = MultiValueDict()
示例9: make_url
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
def make_url(to, args=(), kwargs={}, keep_params=False, params=None,
append=None, request=None, include=None, exclude=None, fragment=None, absolute=False):
'''Build an URL from a relative or absolute path, a model instance, a view
name or view function.
If you pass a request you can ask to keep params from it, exclude some
of them or include only a subset of them.
You can set parameters or append to existing one.
'''
url = resolve_url(to, *args, **kwargs)
scheme, netloc, path, query_string, o_fragment = urlparse.urlsplit(url)
url = urlparse.urlunsplit((scheme, netloc, path, '', ''))
fragment = fragment or o_fragment
# Django < 1.6 compat, query_string is not optional
url_params = QueryDict(query_string=query_string, mutable=True)
if keep_params:
assert request is not None, 'missing request'
for key, value in request.GET.iteritems():
if exclude and key in exclude:
continue
if include and key not in include:
continue
url_params.setlist(key, request.GET.getlist(key))
if params:
for key, value in params.iteritems():
if isinstance(value, (tuple, list)):
url_params.setlist(key, value)
else:
url_params[key] = value
if append:
for key, value in append.iteritems():
if isinstance(value, (tuple, list)):
url_params.extend({key: value})
else:
url_params.appendlist(key, value)
if url_params:
url += '?%s' % url_params.urlencode(safe='/')
if fragment:
url += '#%s' % fragment
if absolute:
if request:
url = request.build_absolute_uri(url)
else:
raise TypeError('make_url() absolute cannot be used without request')
return url
示例10: handle_moved_contributors
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
def handle_moved_contributors(self, data, **kwargs):
"""
Work around https://code.djangoproject.com/ticket/25139
Basically, if the user assigns a contributor who already has a contribution to a new contribution,
this moves the contributor (and all the data of the new form they got assigned to) back to the original contribution.
"""
if data is None or "instance" not in kwargs:
return data
course = kwargs["instance"]
total_forms = int(data["contributions-TOTAL_FORMS"])
for i in range(0, total_forms):
prefix = "contributions-" + str(i) + "-"
current_id = data.get(prefix + "id", "")
contributor = data.get(prefix + "contributor", "")
if contributor == "":
continue
# find the contribution that the contributor had before the user messed with it
try:
previous_id = str(Contribution.objects.get(contributor=contributor, course=course).id)
except Contribution.DoesNotExist:
continue
if current_id == previous_id:
continue
# find the form with that previous contribution and then swap the contributions
for j in range(0, total_forms):
other_prefix = "contributions-" + str(j) + "-"
other_id = data[other_prefix + "id"]
if other_id == previous_id:
# swap all the data. the contribution's ids stay in place.
data2 = data.copy()
data = QueryDict(mutable=True)
for key, value in data2.lists():
if not key.endswith("-id"):
key = (
key.replace(prefix, "%temp%")
.replace(other_prefix, prefix)
.replace("%temp%", other_prefix)
)
data.setlist(key, value)
break
return data
示例11: create_next_domains_url
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
def create_next_domains_url(path, scheme="http", domain="", query_params={},
clone_domains=()):
""" handy function to create an url with clone domains querystring"""
# Set the correct params (clones and redirect url)
# Small hack to create automatically the url :P
params = QueryDict(mutable=True)
for k, v in query_params.items():
params[k] = v
if len(clone_domains) > 0:
params.setlist('clone-domains', clone_domains)
url = urllib.parse.ParseResult(
scheme=scheme,
netloc=domain,
path=path,
params="",
query=params.urlencode(),
fragment="", )
return url.geturl()
示例12: UrlHelper
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
class UrlHelper(object):
def __init__(self, full_path):
url = urlparse.urlparse(full_path)
self.path = url.path
self.fragment = url.fragment
self.query_dict = QueryDict(url.query, mutable=True)
def update_query_data(self, **kwargs):
for key, val in kwargs.iteritems():
if hasattr(val, '__iter__'):
self.query_dict.setlist(key, val)
else:
self.query_dict[key] = val
def get_full_path(self, **kwargs):
query_string = self.get_query_string(**kwargs)
if query_string:
query_string = '?' + query_string
fragment = self.fragment and '#' + iri_to_uri(self.fragment) or ''
return iri_to_uri(self.path) + query_string + fragment
def get_query_string(self, **kwargs):
return self.query_dict.urlencode(**kwargs)
示例13: UrlHelper
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
class UrlHelper(object):
def __init__(self, full_path):
# If full_path is an UrlHelper instance, extract the full path from it
if type(full_path) is UrlHelper:
full_path = full_path.get_full_path()
# parse the path
r = urlparse.urlparse(full_path)
self.path = r.path
self.fragment = r.fragment
self.query_dict = QueryDict(smart_bytes(r.query), mutable=True)
def get_query_string(self, **kwargs):
return self.query_dict.urlencode(**kwargs)
def get_query_data(self):
return self.query_dict
def update_query_data(self, **kwargs):
for key, val in kwargs.iteritems():
if hasattr(val, '__iter__'):
self.query_dict.setlist(key, val)
else:
self.query_dict[key] = val
def get_path(self):
return self.path
def get_full_path(self, **kwargs):
query_string = self.get_query_string(**kwargs)
if query_string:
query_string = '?%s' % query_string
fragment = self.fragment and '#%s' % iri_to_uri(self.fragment) or ''
return '%s%s%s' % (
iri_to_uri(self.get_path()),
query_string,
fragment
)
def get_full_quoted_path(self, **kwargs):
return urllib.quote_plus(self.get_full_path(**kwargs), safe='/')
def overload_params(self, **kwargs):
for key, val in kwargs.iteritems():
uniques = set(self.query_dict.getlist(key))
uniques.add(val)
self.query_dict.setlist(key, list(uniques))
def del_param(self, param):
try:
del self.query_dict[param]
except KeyError:
pass # Fail silently
def del_params(self, *params, **kwargs):
if not params and not kwargs:
self.query = {}
return
if params:
for param in params:
self.del_param(param)
if kwargs:
for key, val in kwargs.iteritems():
to_keep = [x for x in self.query_dict.getlist(key)
if not x.startswith(val)]
self.query_dict.setlist(key, to_keep)
def toggle_params(self, **params):
for param, value in params.items():
value = unicode(value)
if value in self.query_dict.getlist(param):
self.del_params(**{param: value})
else:
self.overload_params(**{param: value})
@property
def hash(self):
md5 = hashlib.md5()
md5.update(self.get_full_path())
return md5.hexdigest()
@property
def query(self):
return self.get_query_data()
@query.setter
def query(self, value):
if type(value) is dict:
self.query_dict = QueryDict(b'', mutable=True)
self.update_query_data(**value)
else:
self.query_dict = QueryDict(smart_bytes(value), mutable=True)
@property
def query_string(self):
return self.get_query_string()
@query_string.setter
def query_string(self, value):
#.........这里部分代码省略.........
示例14: cast_to_queryDict
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
def cast_to_queryDict(self, original_dict):
data_query_dict = QueryDict('', mutable=True)
for key, val in original_dict.items():
data_query_dict.setlist(key, val)
return data_query_dict
示例15: fill_form_with_dummy_data
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import setlist [as 别名]
def fill_form_with_dummy_data(self, form, post_data=None):
import django.forms.fields
import django.forms.widgets
try:
from captcha.widgets import ReCaptcha
except ImportError:
ReCaptcha = None
if post_data is None:
post_data = {}
else:
post_data = dict(post_data)
fields_to_delete = []
for field in form:
if field.field.required and not post_data.get(field.name):
widget = field.field.widget
if isinstance(widget, django.forms.widgets.Select):
choices = list(widget.choices)
if not choices:
choices = list(field.field.choices)
possible_values = [v for v, label in choices]
if isinstance(widget, django.forms.widgets.SelectMultiple):
value = [possible_values[0]]
else:
value = possible_values[0]
elif isinstance(field.field, django.forms.fields.EmailField):
value = "[email protected]"
elif isinstance(widget, ReCaptcha):
fields_to_delete.append(field.name)
continue
else:
value = "Whee"
post_data[field.name] = value
query_dict = QueryDict('', mutable=True).copy()
for key, value in post_data.iteritems():
if hasattr(value, '__iter__'):
query_dict.setlist(key, value)
else:
query_dict.setlist(key, [value])
query_dict._mutable = False
new_form = form.__class__(query_dict)
for field_name in fields_to_delete:
del new_form.fields[field_name]
# post_data is not very useful if fields_to_delete is not empty,
# because any form constructed with it won't validate, but it is
# useful under some circumstances, so return it anyway.
"""
if fields_to_delete:
post_data = None
"""
return new_form, post_data