KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
urlparse.parse_qs is usefull for parsing url parameters, and it works fine with simple ASCII url, represented by str . So i can parse a query and then construct the same path using urllib.urlencode from parsed data: >>> import urlparse >>> import urllib >>> >>> path = '/?key=value' #path is str >>> query = urlparse.urlparse(path).query >>> query 'key=value' >>> query_dict = urlparse.parse_qs(query) >>> query_dict {'key': ['value']} >>> '/?' + urllib.urlencode(query_dict, doseq=True) '/?key=value' # <-- path is the same here It also works fine, when url contains percent encoded non-ASCII param: >>> value = urllib.quote(u'значение'.encode('utf8')) >>> value '%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5' >>> path = '/?key=%s' % value >>> path '/?key=%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5' >>> query = urlparse.urlparse(path).query >>> query 'key=%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5' >>> query_dict = urlparse.parse_qs(query) >>> query_dict {'key': ['\xd0\xb7\xd0\xbd\xd0\xb0\xd1\x87\xd0\xb5\xd0\xbd\xd0\xb8\xd0\xb5']} >>> '/?' + urllib.urlencode(query_dict, doseq=True) '/?key=%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5' # <-- path is the same here But, when using django, i get the url using request.get_full_path() , and it returns path as unicode string: >>> path = request.get_full_path() >>> path u'/?key=%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5' # path is unicode Look what will happen now: >>> query = urlparse.urlparse(path).query >>> query u'key=%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5' >>> query_dict = urlparse.parse_qs(query) >&
Tags (comma-separated)
Save Edits
Cancel