Search code examples
pythonsqlitecurlpostbottle

How to send JSON data to a bottle server and store the value in sqlite3?


I have JSON file data.json that I want to send via curl to a bottle server which then take the values from the file. The problem is that it doesn't store anything in the database. How can I do to store the values I pass through the JSON file?

curl command

curl -X POST -i -d @data.json --header "Content-Type: application/json" http://192.168.1.12:8080/

bottle.py

@route('/', method='POST')
def index():
    n1 = request.POST.get("maclist", "").strip()
    n2 = request.POST.get("signallist", "").strip()

    conn = sqlite3.connect('db/users.db')
    c = conn.cursor()
    c.execute("INSERT INTO users (MAC,SIGNAL) VALUES(?,?)", (n1,n2))

    conn.commit()
    return "Items added."

data.json

{
    "maclist": [
        "a1:b2:c3:d4:e5:f6"
    ],
    "signallist": [
        "-25"
    ]
}

Solution

  • Try this way,,,

    client-side

    curl -X POST -i -d @data.json --header "Content-Type: application/json" http://192.168.1.12:8080/
    

    server-side

    @route('/', method='POST')
    def index():
        body = request.body.read().decode('utf8') # read directly HTTP input
        get_dict = json.loads(body) # decode json and get native python dict
        maclist = get_dict.get('maclist', [])
        signallist = get_dict.get('signallist', [])
        data_list = list(zip(maclist, signallist)) # cast to list... You should have same number of elements in both collections (maclist, signallist). Otherwise, zip() function will take collection length which is less.
        conn = sqlite3.connect('db/users.db')
        c = conn.cursor()
        c.executemany("INSERT INTO users (MAC,SIGNAL) VALUES(?,?)", data_list)
    
        conn.commit()
        return "Items added."
    

    I hope,,, it helps you.