如何确保不会在查询字典中消失?
我正在尝试将收到的get-query解析为字典:
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': ['']}>
我想得到以下结果:
<QueryDict: {'test=1+1': ['1+1']}>
这个怎么样?
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']}>
你需要对加号进行百分比编码,通过使用quote_plus
,你也编码了等号(=
),因此QueryDict
不能有效地解析它:
my_safe_string =f'test={quote_plus("1+1")}'
这产生:
>>> from urllib.parse import quote_plus
>>> my_safe_string = f'test={quote_plus("1+1")}'
>>> QueryDict(my_safe_string)
<QueryDict: {'test': ['1+1']}>
如果不清楚该键是否包含需要转义的字符,可以使用:
key = 'test'
value = '1+1'
my_safe_string = f'{quote_plus(key)}={quote_plus(value)}'