TDengine/docs/examples/python/tmq_websocket_example.py

173 lines
5.3 KiB
Python
Raw Normal View History

#!/usr/bin/python3
2024-08-03 10:04:12 +00:00
import taosws
2024-08-05 04:08:17 +00:00
topic = "topic_meters"
2024-08-02 18:51:12 +00:00
def prepareMeta():
conn = None
try:
conn = taosws.connect(user="root",
2024-08-03 10:04:12 +00:00
password="taosdata",
host="localhost",
port=6041)
2024-08-02 18:51:12 +00:00
db = "power"
# create database
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}")
assert rowsAffected == 0
2024-08-03 10:04:12 +00:00
# change database.
2024-08-02 18:51:12 +00:00
rowsAffected = conn.execute(f"USE {db}")
assert rowsAffected == 0
2024-08-03 10:04:12 +00:00
2024-08-02 18:51:12 +00:00
# create super table
rowsAffected = conn.execute(
"CREATE TABLE IF NOT EXISTS `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
)
assert rowsAffected == 0
# create table
2024-08-03 10:04:12 +00:00
rowsAffected = conn.execute(
"CREATE TABLE IF NOT EXISTS `d0` USING `meters` (groupid, location) TAGS(0, 'Los Angles')")
2024-08-02 18:51:12 +00:00
assert rowsAffected == 0
2024-08-05 04:08:17 +00:00
# ANCHOR: create_topic
# create topic
conn.execute(
f"CREATE TOPIC IF NOT EXISTS {topic} AS SELECT ts, current, voltage, phase, groupid, location FROM meters"
)
# ANCHOR_END: create_topic
2024-08-02 18:51:12 +00:00
sql = """
INSERT INTO
power.d1001 USING power.meters (groupid, location) TAGS(2, 'California.SanFrancisco')
VALUES (NOW + 1a, 10.30000, 219, 0.31000)
(NOW + 2a, 12.60000, 218, 0.33000) (NOW + 3a, 12.30000, 221, 0.31000)
power.d1002 USING power.meters (groupid, location) TAGS(3, 'California.SanFrancisco')
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
"""
2024-08-03 10:04:12 +00:00
affectedRows = conn.execute(sql)
2024-08-12 12:21:16 +00:00
print(f"Inserted into {affectedRows} rows to power.meters successfully.")
2024-08-02 18:51:12 +00:00
except Exception as err:
2024-08-12 11:33:50 +00:00
print(f"Failed to prepareMeta ErrMessage:{err}")
2024-08-03 10:04:12 +00:00
raise err
2024-08-02 18:51:12 +00:00
finally:
if conn:
conn.close()
2024-08-03 10:04:12 +00:00
2024-08-02 18:51:12 +00:00
# ANCHOR: create_consumer
def create_consumer():
2024-08-12 06:13:31 +00:00
host = "localhost"
port = 6041
groupId = "group1"
clientId = "1"
2024-08-02 18:51:12 +00:00
try:
consumer = taosws.Consumer(conf={
"td.connect.websocket.scheme": "ws",
2024-08-12 06:13:31 +00:00
"group.id": groupId,
"client.id": clientId,
2024-08-02 18:51:12 +00:00
"auto.offset.reset": "latest",
2024-08-12 06:13:31 +00:00
"td.connect.ip": host,
"td.connect.port": port,
2024-08-02 18:51:12 +00:00
"enable.auto.commit": "true",
2024-08-03 10:04:12 +00:00
"auto.commit.interval.ms": "1000",
2024-08-02 18:51:12 +00:00
})
2024-08-12 06:13:31 +00:00
print(f"Create consumer successfully, host: {host}:{port}, groupId: {groupId}, clientId: {clientId}");
2024-08-02 18:51:12 +00:00
return consumer;
except Exception as err:
2024-08-14 08:25:22 +00:00
print(f"Failed to create websocket consumer, host: {host}:{port}, ErrMessage:{err}");
2024-08-02 18:51:12 +00:00
raise err
2024-08-03 10:04:12 +00:00
2024-08-02 18:51:12 +00:00
# ANCHOR_END: create_consumer
def seek_offset(consumer):
# ANCHOR: assignment
try:
assignments = consumer.assignment()
for assignment in assignments:
topic = assignment.topic()
print(f"topic: {topic}")
for assign in assignment.assignments():
2024-08-03 10:04:12 +00:00
print(
f"vg_id: {assign.vg_id()}, offset: {assign.offset()}, begin: {assign.begin()}, end: {assign.end()}")
2024-08-02 18:51:12 +00:00
consumer.seek(topic, assign.vg_id(), assign.begin())
2024-08-12 12:21:16 +00:00
print("Assignment seek to beginning successfully");
2024-08-03 10:04:12 +00:00
2024-08-02 18:51:12 +00:00
except Exception as err:
2024-08-14 08:25:22 +00:00
print(f"Failed to execute seek example, ErrMessage:{err}")
2024-08-02 18:51:12 +00:00
raise err
# ANCHOR_END: assignment
2024-08-03 10:04:12 +00:00
2024-08-02 18:51:12 +00:00
# ANCHOR: subscribe
def subscribe(consumer):
try:
2024-08-05 04:08:17 +00:00
consumer.subscribe([topic])
2024-08-12 12:21:16 +00:00
print("Subscribe topics successfully")
2024-08-05 04:08:17 +00:00
for i in range(50):
2024-08-02 18:51:12 +00:00
records = consumer.poll(timeout=1.0)
if records:
for block in records:
for row in block:
2024-08-12 06:13:31 +00:00
print(f"data: {row}")
2024-08-02 18:51:12 +00:00
except Exception as err:
2024-08-12 11:33:50 +00:00
print(f"Failed to poll data, ErrMessage:{err}")
2024-08-02 18:51:12 +00:00
raise err
2024-08-03 10:04:12 +00:00
2024-08-02 18:51:12 +00:00
# ANCHOR_END: subscribe
# ANCHOR: commit_offset
def commit_offset(consumer):
try:
2024-08-05 04:08:17 +00:00
for i in range(50):
2024-08-02 18:51:12 +00:00
records = consumer.poll(timeout=1.0)
if records:
for block in records:
for row in block:
2024-08-12 06:13:31 +00:00
print(f"data: {row}")
2024-08-03 15:32:14 +00:00
# after processing the data, commit the offset manually
2024-08-02 18:51:12 +00:00
consumer.commit(records)
2024-08-12 12:21:16 +00:00
print("Commit offset manually successfully.");
2024-08-02 18:51:12 +00:00
except Exception as err:
2024-08-14 08:25:22 +00:00
print(f"Failed to execute commit example, ErrMessage:{err}")
2024-08-02 18:51:12 +00:00
raise err
2024-08-03 10:04:12 +00:00
# ANCHOR_END: commit_offset
#
2024-08-12 14:55:35 +00:00
2024-08-02 18:51:12 +00:00
def unsubscribe(consumer):
2024-08-12 14:55:35 +00:00
# ANCHOR: unsubscribe
2024-08-02 18:51:12 +00:00
try:
consumer.unsubscribe()
2024-08-12 12:21:16 +00:00
print("Consumer unsubscribed successfully.");
2024-08-02 18:51:12 +00:00
except Exception as err:
2024-08-12 11:33:50 +00:00
print(f"Failed to unsubscribe consumer. ErrMessage:{err}")
2024-08-12 14:55:35 +00:00
finally:
if consumer:
2024-08-14 08:25:22 +00:00
consumer.close()
print("Consumer closed successfully.");
2024-08-03 10:04:12 +00:00
2024-08-02 18:51:12 +00:00
# ANCHOR_END: unsubscribe
if __name__ == "__main__":
consumer = None
2024-08-03 10:04:12 +00:00
try:
2024-08-02 18:51:12 +00:00
prepareMeta()
consumer = create_consumer()
subscribe(consumer)
seek_offset(consumer)
2024-08-12 14:55:35 +00:00
commit_offset(consumer)
2024-08-02 18:51:12 +00:00
except Exception as err:
2024-08-14 08:25:22 +00:00
print(f"Failed to execute consumer example, ErrorMessage:{err}")
2024-08-02 18:51:12 +00:00
finally:
2024-08-14 08:25:22 +00:00
unsubscribe(consumer);