[英]Django QueryDict How to ensure that the "plus" does not disappear in the QueryDict?
How to ensure that the "plus" does not disappear in the QueryDict?如何确保“加号”不会在 QueryDict 中消失?
I am trying to parse the received get-query into a dict:我正在尝试将接收到的 get-query 解析为一个 dict:
from urllib.parse import quote_plus
my_non_safe_string = "test=1+1" # This example, the string can be anything. (in GET query format)
QueryDict(my_non_safe_string)
out: <QueryDict: {'test': ['1 1']}>
my_safe_string = quote_plus("test=1+1") # 'test%3D1%2B1'
out: <QueryDict: {'test=1+1': ['']}>
I would like to get the following result:我想得到以下结果:
<QueryDict: {'test=1+1': ['1+1']}>
You need to percentage encode the plus, by use quote_plus
you also encode the equal sign ( =
) and therefore the QueryDict
can not parse it effectively:您需要对加号进行百分比编码,通过使用
quote_plus
您还对等号 ( =
) 进行编码,因此QueryDict
无法有效解析它:
my_safe_string = f'test={quote_plus("1+1")}'
this produces:这产生:
>>> from urllib.parse import quote_plus
>>> my_safe_string = f'test={quote_plus("1+1")}'
>>> QueryDict(my_safe_string)
<QueryDict: {'test': ['1+1']}>
If it is unclear if the key contains any characters that should be escaped, you can use:如果不清楚密钥是否包含任何应该转义的字符,您可以使用:
key = 'test'
value = '1+1'
my_safe_string = f'{ quote_plus(key) }={ quote_plus(value) }'
How about this?这个怎么样?
In [1]: from django.http import QueryDict
In [2]: from urllib.parse import quote_plus
In [3]: key = quote_plus("test=1+1")
In [4]: value = quote_plus("1+1")
In [5]: query_str = f"{key}={value}"
In [6]: QueryDict(query_str)
Out[6]: <QueryDict: {'test=1+1': ['1+1']}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.