Python request using ast.literal_eval error Invalid syntax?

ⅰ亾dé卋堺 提交于 2019-12-11 02:49:52

问题


i am new to python and trying to get request data using ast.literal_eval resulting in "invalid syntax" error.

It prints data i send that is format like,

192.156.1.0,8181,database,admin,12345

In python i display it but get error while reading it my code is,

    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']

Invalid syntax error on line data=ast.literal_eval(datas)

How to resolve it suggestion will be appreciable

Thanks


回答1:


change this:

192.156.1.0,8181,database,admin,12345

to this:

>>> 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 

arbitrarily complex expressions, for example involving operators or indexing.

you can try like this:

>>> 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']

your code will look like this:

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



回答2:


What about something like

dbname, username, ip, port, pwd = request.body.read().split(',')

Test

>>> 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'


来源:https://stackoverflow.com/questions/27055826/python-request-using-ast-literal-eval-error-invalid-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!