Search code examples
questdb

How do I write influx line protocol records to QuestDB using Python?


How can I send influx line protocol messages to QuestDB from python? Should I be using a library or should I write to the socket? The node example looks like

const net = require("net")

const client = new net.Socket()

const HOST = "localhost"
const PORT = 9009

function run() {
  client.connect(PORT, HOST, () => {
    const rows = [
      `trades,name=test_ilp1 value=12.4 ${Date.now() * 1e6}`,
      `trades,name=test_ilp2 value=11.4 ${Date.now() * 1e6}`,
    ]

    rows.forEach((row) => {
      client.write(`${row}\n`)
    })

    client.destroy()
  })

  client.on("data", function (data) {
    console.log("Received: " + data)
  })

  client.on("close", function () {
    console.log("Connection closed")
  })
}

run()

Solution

  • The Python equivalent for the example looks something like the following:

    import time
    import socket
    
    HOST = 'localhost'
    PORT = 9009
    
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
    try:
      sock.sendto(('trades,name=test_ilp1 value=12.4 %d' % (time.time_ns())).encode(), (HOST, PORT))
      sock.sendto(('trades,name=test_ilp2 value=11.4 %d' % (time.time_ns())).encode(), (HOST, PORT))
    except socket.error as e:
      print("Got error: %s" % (e))
    sock.close()
    

    Note that calling time.time_ns() inside the influx line message is optional, so you can omit it and the server will assign the system time as a timestamp for the row. For the format of incoming messages, you can find a reference on the questdb influx docs