Search code examples
pythonjsonparsinghttphttprequest

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


Solution

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