简体   繁体   中英

Python request using ast.literal_eval error Invalid syntax?

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

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(','))))

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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