【问题标题】:How to send JSON data to a bottle server and store the value in sqlite3?如何将 JSON 数据发送到瓶子服务器并将值存储在 sqlite3 中?
【发布时间】:2019-10-16 12:24:23
【问题描述】:

我有 JSON 文件 data.json 我想通过 curl 发送到一个瓶子服务器,然后从文件中获取值。问题是它没有在数据库中存储任何内容。如何存储通过 JSON 文件传递​​的值?

卷曲命令

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."

数据.json

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

【问题讨论】:

  • 你能在服务器端正确读取maclist和signallist吗?用瓶子?
  • @gachdavit 这正是我想做的。我通过 curl 发送 post 请求,我收到 200。
  • 我添加了答案,检查一下。

标签: python sqlite curl post bottle


【解决方案1】:

试试这个方法,,,

客户端

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

服务器端

@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."

希望对你有帮助。

【讨论】:

  • 另外,不要忘记 maclistsignallist 是键,在您的情况下它们的值是 lists。我们现在只读取第一个元素,您可以在将来对其进行迭代并在数据库中进行批量插入,或者多次访问数据库。如你所愿。
  • 没错,我需要的元素不止一个。问题是我不知道我会有多少元素,那么最好的方法是什么?
  • executemany() 方法正是您想要的。我更新了我的答案,检查一下。
  • 非常感谢,这正是我想要的。
  • 我正在尝试使用 datetime 添加当前日期,所以我使用 c.executemany("INSERT OR REPLACE INTO node2 (MAC,SIGNAL,FECHA) VALUES(?,?,?)", data_list, datetime.now()) 但我收到此错误 TypeError: function takes exactly 2 arguments (3 given)
猜你喜欢
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
  • 1970-01-01
相关资源
最近更新 更多