简体   繁体   English

如何在Python中安全评估urlencode字典?

[英]how to safely eval an urlencode-ed dictionary in Python?

I should communicate with an online service that sends me the following data urlencoded: 我应该与在线服务进行通信,该服务会向我发送以下代码:

data_to_process = {...}
args = {'args0': data_to_process, 'action': 'save'}

result = urllib2.urlopen(..., urllib.urlencode(args), ...)

The main data of interest is stored in the data_to_process dictionary. 感兴趣的主要数据存储在data_to_process词典中。 I would like to get back the original dictionary that's supposed to contain only string, numeric and boolean values. 我想找回原本只包含字符串,数字和布尔值的字典。 How can you achieve this? 你怎么能做到这一点?

I've tried 我试过了

eval(dict_str,{'__builtins__': None})

but this fails for False values (and who knows what else). 但这对于False值(以及谁知道其他什么)失败。

thanks for any ideas! 感谢您的任何想法!

Use ast.literal_eval : 使用ast.literal_eval

>>> from ast import literal_eval
>>> test = repr({"ham": True, 42: "spam", "foo": "bar"})
>>> test
"{42: 'spam', 'foo': 'bar', 'ham': True}"
>>> literal_eval(test)
{42: 'spam', 'foo': 'bar', 'ham': True}

Are you sure that the service isn't sending you JSON? 您确定该服务没有向您发送JSON吗? In which case you can parse it using the built-in json.loads() function (since Python 2.6). 在这种情况下,您可以使用内置的json.loads()函数(自python 2.6起)对其进行解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM