Python request using ast.literal_eval error Invalid syntax?
13,068
Solution 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(','))))
Solution 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'
Author by
user3664724
Updated on June 23, 2022Comments
-
user3664724 almost 2 years
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
-
Hackaholic over 9 yearscant do like this any one can inject malicious code
-
user3664724 over 9 years192.156.1.0,8181,database,admin,12345 is comming from http POST how to change it into string.
-
user3664724 over 9 years192.156.1.0,8181,database,admin,12345 commin from http POST how to convert it into string ?
-
nu11p01n73R over 9 years
str(request.body.read())
will do . same as in your code. see theprint
statement