本文整理汇总了Python中django.http.request.QueryDict.urlencode方法的典型用法代码示例。如果您正苦于以下问题:Python QueryDict.urlencode方法的具体用法?Python QueryDict.urlencode怎么用?Python QueryDict.urlencode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.http.request.QueryDict
的用法示例。
在下文中一共展示了QueryDict.urlencode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_clone_url
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [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])
示例2: do
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [as 别名]
def do(self, action_context, view, email, *args, **kwargs):
# Reset token
user = action_context.extra_context.get('user')
if user:
refresh_password_reset_token(user)
url = reverse('auth:reset-password', kwargs={
'user_id': user.id,
'uuid': str(user.password_reset_token)})
# Prepare the full url (get the domain from the asked
# wiggum entrypoint)
domain = action_context.request.META.get('HTTP_HOST')
scheme = 'http' if settings.DEBUG else "https"
# Get redirection uri
params = QueryDict(mutable=True)
redirect_uri = action_context.extra_context.get("redirect_uri")
if redirect_uri:
params[settings.REDIRECT_URL_VALID_PARAMS[0]] = redirect_uri
url = urllib.parse.ParseResult(scheme=scheme,
netloc=domain,
path=url,
params="",
query=params.urlencode(),
fragment="").geturl()
action_context.extra_context['pass_reset_url'] = url
logger.debug("Password recover url created: {0}".format(url))
return super().do(action_context, view, email, *args, **kwargs)
示例3: encode_data
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [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)
示例4: encode_query
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [as 别名]
def encode_query(querydict):
"""
Encode a querydict as form params, using '+'' for ' '.
"""
if not isinstance(querydict, QueryDict):
temp = querydict
querydict = QueryDict('', mutable=True)
querydict.update(temp)
return querydict.urlencode(': ').replace(' ', '+')
示例5: query_string_from_dict
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [as 别名]
def query_string_from_dict(qs_dict):
qs_prepared_dict = OrderedDict()
for key, val in qs_dict.items():
if isinstance(val, list):
val = '[%s]' % ','.join([force_text(v) for v in val])
qs_prepared_dict[key] = val
qdict = QueryDict('').copy()
qdict.update(qs_prepared_dict)
return qdict.urlencode()
示例6: render
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [as 别名]
def render(self, context):
if not len(self.args) or "=" in self.args[0]:
querydict = QueryDict("", mutable=True)
else:
first = self.args[0]
self.args = self.args[1:]
querydict = Variable(first).resolve(context).copy()
for pair in self.args:
k, v = [Variable(p).resolve(context) for p in pair.split("=")]
querydict[k] = v
return querydict.urlencode()
示例7: url_param_replace
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [as 别名]
def url_param_replace(self, **kwargs):
query = QueryDict(self.request.META['QUERY_STRING'], mutable=True)
for key, value in kwargs.items():
if not key:
query.pop(key, None)
else:
query[key] = value
if query:
return self.request.path_info + '?' + query.urlencode('{}')
else:
return self.request.path_info
示例8: send
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [as 别名]
def send(self, url, message_data, **kwargs):
qs = QueryDict(mutable=True)
qs.update(message_data)
r = urllib.request.urlopen(urllib.request.Request(
url,
qs.urlencode().encode('utf-8'),
))
result = r.read().decode('utf-8')
return self.validate(r.headers['content-type'], result, message_data)
示例9: get
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [as 别名]
def get(self, request, *args, **kwargs):
try:
self.object = self.get_object()
check_album_token_valid_or_user_authenticated(request, album=self.object)
context = self.get_context_data(object=self.object)
context['is_admin'] = (request.user and request.user.is_staff)
if hasattr(settings, 'GOOGLE_ANALYTICS'):
context['GOOGLE_ANALYTICS'] = settings.GOOGLE_ANALYTICS
return self.render_to_response(context)
except UnauthorizedUserException:
url = reverse('auth_login')
q = QueryDict('next=%s' % self.request.path)
url += "?" + q.urlencode(safe='/')
return redirect(url)
示例10: redirect_to_login
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [as 别名]
def redirect_to_login(next, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME, type_code='login'):
"""
Redirects the user to the login page, passing the given 'next' page
"""
resolved_url = resolve_url(login_url or settings.LOGIN_URL)
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_parts[4], mutable=True)
querystring[redirect_field_name] = next
querystring['need'] = type_code
login_url_parts[4] = querystring.urlencode(safe='/')
return HttpResponseRedirect(urlunparse(login_url_parts))
示例11: on_user_logged_out
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [as 别名]
def on_user_logged_out(sender, request, user, **kwargs):
if not settings.AUTH_OPENID:
return
query = QueryDict('', mutable=True)
query.update({
'redirect_uri': settings.BASE_SITE_URL
})
openid_logout_url = "%s?%s" % (
client.openid_connect_client.get_url(
name='end_session_endpoint'),
query.urlencode()
)
request.COOKIES['next'] = openid_logout_url
示例12: search
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [as 别名]
def search(request):
queryDict = QueryDict(mutable=True)
queryDict['q'] = request.GET['search']
if 'pageSize' in request.GET:
queryDict['size'] = request.GET['pageSize']
if 'pageNumber' in request.GET:
queryDict['page'] = request.GET['pageNumber']
photoBase = "http://assets.epicurious.com/photos/%s/1:1/w_600%%2Ch_600/%s"
response = requests.get("http://services.epicurious.com/api/search/v1/query?" + queryDict.urlencode())
bundle = json.loads(response.text.encode('utf-8'))
start = bundle["start"]
numFound = bundle["numFound"]
totalPages = bundle["totalPages"]
recipes = []
if start < numFound :
for recipe in bundle["items"] :
if recipe["type"] == "recipe":
rec = {}
rec["name"]= recipe["hed"]
rec["id"] = recipe["url"]
if "aggregateRating" in recipe:
rec["rating"] = recipe["aggregateRating"]
if "photoData" in recipe:
rec["image"] = photoBase % (recipe["photoData"]["id"], recipe["photoData"]["filename"])
recipes.append(rec)
response = {}
response["recipes"] = recipes
response["start"] = start
response["numFound"] = numFound
response["totalPages"] = totalPages
json_string = json.dumps(response, indent=4)
# "numFound":477,"start":460,"rows":20,"totalPages":24
# items = [{hed, type, aggregateRating, url, photoData: {}}]
return HttpResponse(json_string, content_type="application/json; charset=utf-8")
示例13: format_filter
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [as 别名]
def format_filter(self, obj):
qd = QueryDict(mutable=True)
filter_fields = self.filter.keys()
for field_name in filter_fields:
try:
# check if serializer method passed in
serializer_method = getattr(self.parent, self.filter[field_name])
except AttributeError:
value = self.lookup_attribute(obj, self.filter[field_name])
else:
value = serializer_method(obj)
if not value:
continue
qd.update({'[{}]'.format(field_name): value})
if not qd.keys():
return None
return qd.urlencode(safe=['[', ']'])
示例14: make_url
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [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
示例15: plugin_caller
# 需要导入模块: from django.http.request import QueryDict [as 别名]
# 或者: from django.http.request.QueryDict import urlencode [as 别名]
def plugin_caller(specs, query):
p = compile("(^.+?)_.*$") # Add '?' to prevent greedy matching
unique_plugins = set(str(p.match(s).groups(0)[0]) for s in query.keys() if p.match(s))
plugin_funcs = JSCommand.get_functions()
for p in unique_plugins:
# print("plugin: ", p,plugins.base.plugin_funcs.keys())
if plugin_funcs.has_key(p):
start=len(p+"_")
params = {k[start:]:v for (k,v) in query.items() if k.startswith(p+"_") and len(k) > start}
query_params = QueryDict('', mutable=True)
query_params.update({k:v for (k,v) in query.items() if k.startswith(p+"_")})
params['query_params'] = query_params.urlencode()
specs = plugin_funcs[p](specs, params)
#print(plugin_funcs[p].__name__)
#import pdb; pdb.set_trace()
else:
raise exceptions.PluginNotFoundError('Can\'t find plugin %s' %p)
return specs