如何将 JSON 数据发送到瓶服务器并将值存储在 sqlite3 中?
How to send JSON data to a bottle server and store the value in sqlite3?
我有 JSON 文件 data.json,我想通过 curl 将其发送到瓶服务器,然后从文件中获取值。问题是它不在数据库中存储任何内容。如何存储通过 JSON 文件传递的值?
curl 命令
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"
]
}
这样试试,
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."
希望,对你有帮助
我有 JSON 文件 data.json,我想通过 curl 将其发送到瓶服务器,然后从文件中获取值。问题是它不在数据库中存储任何内容。如何存储通过 JSON 文件传递的值?
curl 命令
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"
]
}
这样试试,
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."
希望,对你有帮助