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,a
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'
Post a Comment for "Python Request Using Ast.literal_eval Error Invalid Syntax?"