使用ast.literal_eval的Python请求错误语法无效?

时间:2014-11-21 07:00:20

标签: python json parsing http httprequest

我是python的新手并尝试使用ast.literal_eval获取请求数据,导致“语法无效”错误。

它打印我发送的格式为

的数据
192.156.1.0,8181,database,admin,12345

在python中我显示它但在读取时出错我的代码是,

    print str(request.body.read())
    datas = request.body.read()
    data=ast.literal_eval(datas)
    dbname = data['dbname']
    username = data['uname']
    ip = data['ip']
    port = data['port']
    pwd = data['pwd']

data = ast.literal_eval(datas)

上的语法错误无效

如何解决它的建议将会很明显

谢谢

2 个答案:

答案 0 :(得分:3)

改变这个:

192.156.1.0,8181,database,admin,12345

到此:

>>> a = "['192.156.1.0',8181,'database','admin',12345]"
>>> ast.literal_eval(a)
['192.156.1.0', 8181, 'database', 'admin', 12345]

ast.literal_eval

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing
a Python literal or container display. The string or node provided may only consist of 
the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

 This can be used for safely evaluating strings containing Python values from untrusted 
sources without the need to parse the values oneself. It is not capable of evaluating 

任意复杂的表达式,例如涉及运算符或索引。

你可以这样试试:

>>> a='192.156.1.0,8181,database,admin,12345'
>>> a = str(map(str,a.split(',')))
>>> a
"['192.156.1.0', '8181', 'database', 'admin', '12345']"
>>> ast.literal_eval(a)
['192.156.1.0', '8181', 'database', 'admin', '12345']

您的代码将如下所示:

data=ast.literal_eval(str(map(str,datas.split(','))))

答案 1 :(得分:2)

这样的东西
dbname, username, ip, port, pwd = request.body.read().split(',')

<强>测试

>>> str = "192.156.1.0,8181,database,admin,12345"
>>> dbname , username , ip, port ,pwd = str.split(',')
>>> dbname
'192.156.1.0'
>>> username
'8181'
>>> ip
'database'
>>> port
'admin'
>>> pwd
'12345'