add python example

This commit is contained in:
menshibin 2024-08-03 21:58:17 +08:00 committed by gccgdb1234
parent 2f20970190
commit 04f9a611c0
17 changed files with 121 additions and 223 deletions

View File

@ -3,15 +3,18 @@ import taos
def create_connection(): def create_connection():
# all parameters are optional. # all parameters are optional.
conn = None conn = None
host = "localhost"
port = 6030
try: try:
conn = taos.connect( conn = taos.connect(
user="root", user="root",
password="taosdata", password="taosdata",
host="localhost", host=host,
port=6030, port=port,
) )
print(f"Connected to {host}:{port} successfully.");
except Exception as err: except Exception as err:
print(err) print(f"Failed to connect to {host}:{port} ; Err:{err}")
finally: finally:
if conn: if conn:
conn.close() conn.close()

View File

@ -3,16 +3,16 @@ import taosrest
def create_connection(): def create_connection():
conn = None conn = None
url="http://localhost:6041"
try: try:
conn = taosrest.connect(url="http://localhost:6041", conn = taosrest.connect(url=url,
user="root", user="root",
password="taosdata", password="taosdata",
timeout=30) timeout=30)
print("Connection established") print(f"Connected to {url} successfully.");
except Exception as err: except Exception as err:
print(err) print(f"Failed to connect to {url} ; Err:{err}")
finally: finally:
if conn: if conn:
conn.close() conn.close()

View File

@ -3,36 +3,35 @@ import taosws
def create_connection(): def create_connection():
conn = None conn = None
host = "localhost"
port = 6041
try: try:
conn = taosws.connect( conn = taosws.connect(
user="root", user="root",
password="taosdata", password="taosdata",
host="localhost", host=host,
port=6041, port=port,
) )
print(f"Connected to {host}:{port} successfully.");
except Exception as err: except Exception as err:
print(err) print(f"Failed to connect to {host}:{port} ; Err:{err}")
return conn return conn
# ANCHOR_END: connect
# ANCHOR_END: connect
def create_db_table(conn): def create_db_table(conn):
# ANCHOR: create_db # ANCHOR: create_db
try: try:
conn.execute("CREATE DATABASE IF NOT EXISTS power") conn.execute("CREATE DATABASE IF NOT EXISTS power")
conn.execute("USE power") conn.execute("USE power")
conn.execute( conn.execute("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
"CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
conn.execute("CREATE TABLE IF NOT EXISTS `d0` USING `meters` (groupId, location) TAGS(0, 'Los Angles')") conn.execute("CREATE TABLE IF NOT EXISTS `d0` USING `meters` (groupId, location) TAGS(0, 'Los Angles')")
except Exception as err: except Exception as err:
print(f'Exception {err}') print(f'Exception {err}')
# ANCHOR_END: create_db # ANCHOR_END: create_db
def insert(conn): def insert(conn):
# ANCHOR: insert # ANCHOR: insert
sql = """ sql = """
INSERT INTO INSERT INTO
power.d1001 USING power.meters TAGS('California.SanFrancisco', 2) power.d1001 USING power.meters TAGS('California.SanFrancisco', 2)
@ -43,26 +42,22 @@ def insert(conn):
""" """
try: try:
inserted = conn.execute(sql) inserted = conn.execute(sql)
assert inserted == 4 assert inserted == 8
except Exception as err: except Exception as err:
print(f'Exception {err}') print(f'Exception111 {err}')
# ANCHOR_END: insert # ANCHOR_END: insert
def query(conn): def query(conn):
# ANCHOR: query # ANCHOR: query
try: try:
result = conn.query("select * from meters") result = conn.query("select * from meters")
num_of_fields = result.field_count num_of_fields = result.field_count
print(f"query field conunt is {num_of_fields}") print(num_of_fields)
for row in result: for row in result:
print(row) print(row)
except Exception as err: except Exception as err:
print(f'query Exception {err}') print(f'Exception {err}')
# ANCHOR_END: query # ANCHOR_END: query
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -1,11 +1,13 @@
import taos import taos
conn = None conn = None
host = "localhost"
port = 6030
try: try:
conn = taos.connect(host="localhost", conn = taos.connect(host=host,
port=port,
user="root", user="root",
password="taosdata", password="taosdata")
port=6030)
db = "power" db = "power"
# create database # create database
@ -27,7 +29,7 @@ try:
assert rowsAffected == 0 assert rowsAffected == 0
except Exception as err: except Exception as err:
print(err) print(f"Failed to create db and table, db addrr:{host}:{port} err:{err}")
finally: finally:
if conn: if conn:
conn.close() conn.close()

View File

@ -1,8 +1,9 @@
import taosrest import taosrest
conn = None conn = None
url = "http://localhost:6041"
try: try:
conn = taosrest.connect(url="http://localhost:6041", conn = taosrest.connect(url=url,
user="root", user="root",
password="taosdata", password="taosdata",
timeout=30) timeout=30)
@ -22,7 +23,7 @@ try:
assert rowsAffected == 0 assert rowsAffected == 0
except Exception as err: except Exception as err:
print(err) print(f"Failed to create db and table, url:{url} err:{err}")
finally: finally:
if conn: if conn:
conn.close() conn.close()

View File

@ -1,76 +1,35 @@
import taosws import taosws
db = "power" conn = None
host = "localhost"
def prepare(): port = 6041
conn = None try:
try:
conn = taosws.connect(user="root", conn = taosws.connect(user="root",
password="taosdata", password="taosdata",
host="192.168.1.98", host=host,
port=6041) port=port)
db = "power"
# create database # create database
conn.execute(f"drop database if exists {db}") rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}")
conn.execute(f"create database {db}") assert rowsAffected == 0
except Exception as err:
print(err) # change database.
finally: rowsAffected = conn.execute(f"USE {db}")
assert rowsAffected == 0
# 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
rowsAffected = conn.execute("CREATE TABLE IF NOT EXISTS `d0` USING `meters` (groupid, location) TAGS(0, 'Los Angles')")
assert rowsAffected == 0
except Exception as err:
print(f"Failed to create db and table, db addrr:{host}:{port} err:{err}")
finally:
if conn: if conn:
conn.close() conn.close()
def schemaless_insert():
conn = None
lineDemo = [
"meters,groupid=2,location=California.SanFrancisco current=10.3000002f64,voltage=219i32,phase=0.31f64 1626006833639"
]
telnetDemo = ["metric_telnet 1707095283260 4 host=host0 interface=eth0"]
jsonDemo = [
'{"metric": "metric_json","timestamp": 1626846400,"value": 10.3, "tags": {"groupid": 2, "location": "California.SanFrancisco", "id": "d1001"}}'
]
try:
conn = taosws.connect(user="root",
password="taosdata",
host="192.168.1.98",
port=6041,
database=db)
conn.schemaless_insert(
lines=lineDemo,
protocol=taosws.PySchemalessProtocol.Line,
precision=taosws.PySchemalessPrecision.Millisecond,
ttl=1,
req_id=1,
)
conn.schemaless_insert(
lines=telnetDemo,
protocol=taosws.PySchemalessProtocol.Telnet,
precision=taosws.PySchemalessPrecision.Microsecond,
ttl=1,
req_id=2,
)
conn.schemaless_insert(
lines=jsonDemo,
protocol=taosws.PySchemalessProtocol.Json,
precision=taosws.PySchemalessPrecision.Millisecond,
ttl=1,
req_id=3,
)
except Exception as err:
print(err)
finally:
if conn:
conn.close()
if __name__ == '__main__':
prepare()
schemaless_insert()

View File

@ -20,7 +20,7 @@ try:
print(row) print(row)
except Exception as err: except Exception as err:
print(err) print(f"Failed to query data from power.meters, err:{err}")
finally: finally:
if conn: if conn:
conn.close() conn.close()

View File

@ -8,8 +8,8 @@ try:
password="taosdata", password="taosdata",
timeout=30) timeout=30)
result = client.sql(f"SELECT ts, current, location FROM power.meters limit 100") result = client.sql(f"SELECT ts, current, location FROM power.meters limit 100", 1)
print(result) print(result)
except Exception as err: except Exception as err:
print(err) print(f"Failed to query data from power.meters, err:{err}")

View File

@ -16,7 +16,7 @@ try:
print(row) print(row)
except Exception as err: except Exception as err:
print(err) print(f"Failed to query data from power.meters, err:{err}")
finally: finally:
if conn: if conn:
conn.close() conn.close()

View File

@ -7,19 +7,7 @@ try:
user="root", user="root",
password="taosdata") password="taosdata")
sql = """ result = conn.query("SELECT ts, current, location FROM power.meters limit 100", 1)
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)
"""
affectedRows = conn.execute(sql, 1)
print(f"inserted into {affectedRows} rows to power.meters successfully.")
result = conn.query("SELECT ts, current, location FROM power.meters limit 100", 2)
print(result)
# Get fields from result # Get fields from result
fields = result.fields fields = result.fields
for field in fields: for field in fields:
@ -31,7 +19,7 @@ try:
print(row) print(row)
except Exception as err: except Exception as err:
print(err) print(f"Failed to execute sql with reqId, err:{err}")
finally: finally:
if conn: if conn:
conn.close() conn.close()

View File

@ -12,4 +12,4 @@ try:
print(result) print(result)
except Exception as err: except Exception as err:
print(err) print(f"Failed to execute sql with reqId, err:{err}")

View File

@ -10,26 +10,13 @@ try:
port=6041, port=6041,
) )
sql = """ result = conn.query_with_req_id("SELECT ts, current, location FROM power.meters limit 100", req_id=1)
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)
"""
affectedRows = conn.execute_with_req_id(sql, req_id=1)
print(f"inserted into {affectedRows} rows to power.meters successfully.")
result = conn.query_with_req_id("SELECT ts, current, location FROM power.meters limit 100", req_id=2)
num_of_fields = result.field_count
print(num_of_fields)
for row in result: for row in result:
print(row) print(row)
except Exception as err: except Exception as err:
print(err) print(f"Failed to execute sql with reqId, err:{err}")
finally: finally:
if conn: if conn:
conn.close() conn.close()

View File

@ -32,7 +32,7 @@ try:
jsonDemo, taos.SmlProtocol.JSON_PROTOCOL, taos.SmlPrecision.MILLI_SECONDS jsonDemo, taos.SmlProtocol.JSON_PROTOCOL, taos.SmlPrecision.MILLI_SECONDS
) )
except Exception as err: except Exception as err:
print(err) print(f"Failed to insert data with schemaless, err:{err}")
finally: finally:
if conn: if conn:
conn.close() conn.close()

View File

@ -1,81 +1,47 @@
import taosws import taosws
db = "power" conn = None
def prepare(): lineDemo = [
conn = None "meters,groupid=2,location=California.SanFrancisco current=10.3000002f64,voltage=219i32,phase=0.31f64 1626006833639"
]
try: telnetDemo = ["metric_telnet 1707095283260 4 host=host0 interface=eth0"]
jsonDemo = [
'{"metric": "metric_json","timestamp": 1626846400,"value": 10.3, "tags": {"groupid": 2, "location": "California.SanFrancisco", "id": "d1001"}}'
]
try:
conn = taosws.connect(user="root", conn = taosws.connect(user="root",
password="taosdata", password="taosdata",
host="taosdata", host="localhost",
port=6041) port=6041)
conn.execute("CREATE DATABASE IF NOT EXISTS power")
# create database conn = conn.execute("USE power")
conn.execute(f"drop database if exists {db}")
conn.execute(f"create database {db}")
except Exception as err:
print(err)
raise err
finally:
if conn:
conn.close()
def schemaless_insert():
conn = None
lineDemo = [
"meters,groupid=2,location=California.SanFrancisco current=10.3000002f64,voltage=219i32,phase=0.31f64 1626006833639"
]
telnetDemo = ["metric_telnet 1707095283260 4 host=host0 interface=eth0"]
jsonDemo = [
'{"metric": "metric_json","timestamp": 1626846400,"value": 10.3, "tags": {"groupid": 2, "location": "California.SanFrancisco", "id": "d1001"}}'
]
try:
conn = taosws.connect(user="root",
password="taosdata",
host="192.168.1.98",
port=6041,
database=db)
conn.schemaless_insert( conn.schemaless_insert(
lines=lineDemo, lines=lineDemo,
protocol=taosws.PySchemalessProtocol.Line, protocol=taosws.PySchemalessProtocol.Line,
precision=taosws.PySchemalessPrecision.Millisecond, precision=taosws.PySchemalessPrecision.Millisecond
ttl=1,
req_id=1,
) )
conn.schemaless_insert( conn.schemaless_insert(
lines=telnetDemo, lines=telnetDemo,
protocol=taosws.PySchemalessProtocol.Telnet, protocol=taosws.PySchemalessProtocol.Telnet,
precision=taosws.PySchemalessPrecision.Microsecond, precision=taosws.PySchemalessPrecision.Microsecond
ttl=1,
req_id=2,
) )
conn.schemaless_insert( conn.schemaless_insert(
lines=jsonDemo, lines=jsonDemo,
protocol=taosws.PySchemalessProtocol.Json, protocol=taosws.PySchemalessProtocol.Json,
precision=taosws.PySchemalessPrecision.Millisecond, precision=taosws.PySchemalessPrecision.Millisecond
ttl=1,
req_id=3,
) )
except Exception as err: except Exception as err:
print(err) print(f"Failed to insert data with schemaless, err:{err}")
raise err
finally: finally:
if conn: if conn:
conn.close() conn.close()
if __name__ == '__main__':
try:
prepare()
schemaless_insert()
except Exception as err:
print(err)

View File

@ -42,7 +42,7 @@ try:
for j in range (numOfRow): for j in range (numOfRow):
timestamps.append(current + i) timestamps.append(current + i)
currents.append(random.random() * 30) currents.append(random.random() * 30)
voltages.append(random.randint(100, 300)) voltages.append(random.random(100, 300))
phases.append(random.random()) phases.append(random.random())
params = taos.new_bind_params(4) params = taos.new_bind_params(4)
@ -52,10 +52,11 @@ try:
params[3].float(phases) params[3].float(phases)
stmt.bind_param_batch(params) stmt.bind_param_batch(params)
stmt.execute() stmt.execute()
print(f"table {tbname} insert ok.") affected = stmt.affected_rows()
print(f"table {tbname} insert {affected} rows.")
except Exception as err: except Exception as err:
print(err) print(f"Failed to insert to table meters using stmt, error: {err}")
finally: finally:
if stmt: if stmt:
stmt.close() stmt.close()

View File

@ -38,10 +38,10 @@ try:
currents = [] currents = []
voltages = [] voltages = []
phases = [] phases = []
for j in range(numOfRow): for j in range (numOfRow):
timestamps.append(current + i) timestamps.append(current + i)
currents.append(random.random() * 30) currents.append(random.random() * 30)
voltages.append(random.randint(100, 300)) voltages.append(random.random(100, 300))
phases.append(random.random()) phases.append(random.random())
stmt.bind_param( stmt.bind_param(
@ -55,10 +55,10 @@ try:
stmt.add_batch() stmt.add_batch()
rows = stmt.execute() rows = stmt.execute()
print(f"table {tbname} insert ok.") print(f"insert {rows} rows.")
except Exception as err: except Exception as err:
print(err) print(f"Failed to insert to table meters using stmt, error: {err}")
finally: finally:
if stmt: if stmt:
stmt.close() stmt.close()

View File

@ -1,6 +1,5 @@
import taos import taos
def prepareMeta(): def prepareMeta():
conn = None conn = None
try: try:
@ -46,12 +45,9 @@ def prepareMeta():
if conn: if conn:
conn.close() conn.close()
# ANCHOR: create_consumer # ANCHOR: create_consumer
from taos.tmq import Consumer from taos.tmq import Consumer
def create_consumer(): def create_consumer():
try: try:
consumer = Consumer( consumer = Consumer(