Skip to main content

TDengine Python Client Library

taospy is the official Python client library for TDengine. taospy provides a rich API that makes it easy for Python applications to use TDengine.

The source code for the Python client library is hosted on GitHub.

Connection types

taospy mainly provides 3 connection types, among which we recommend using websocket connection.

  • Native connection, which correspond to the taos modules of the taospy package, connects to TDengine instances natively through the TDengine client driver (taosc), supporting data writing, querying, subscriptions, schemaless writing, and bind interface.
  • REST connection, which correspond to the taosrest modules of the taospy package, which is implemented through taosAdapter. Some features like schemaless and subscriptions are not supported.
  • Websocket connection taos-ws-py is an optional package to enable using WebSocket to connect TDengine, which is implemented through taosAdapter. The set of features implemented by the WebSocket connection differs slightly from those implemented by the native connection.

For a detailed introduction of the connection types, please refer to: Establish Connection

In addition to wrapping the native and REST interfaces, taospy also provides a set of programming interfaces that conforms to the Python Data Access Specification (PEP 249). It is easy to integrate taospy with many third-party tools, such as SQLAlchemy and pandas.

The direct connection to the server using the native interface provided by the client driver is referred to hereinafter as a "native connection"; the connection to the server using the REST or WebSocket interface provided by taosAdapter is referred to hereinafter as a "REST connection" or "WebSocket connection".

Supported platforms

  • The supported platforms for the native connection are the same as the ones supported by the TDengine client.
  • REST connections are supported on all platforms that can run Python.

Supported features

  • Native connections support all the core features of TDengine, including connection management, SQL execution, bind interface, subscriptions, and schemaless writing.
  • REST connections support features such as connection management and SQL execution. (SQL execution allows you to: manage databases, tables, and supertables, write data, query data, create continuous queries, etc.).

Version selection

We recommend using the latest version of taospy, regardless of the version of TDengine.

Python Client Library Versionmajor changes
2.7.121. added support for varbinary type (STMT does not yet support)
2. improved query performance (thanks to contributor hadrianl)
2.7.9support for getting assignment and seek function on subscription
2.7.8add execute_many method
Python Websocket Connection Versionmajor changes
0.2.9bugs fixes
0.2.51. support for getting assignment and seek function on subscription
2. support schemaless
3. support STMT
0.2.4support unsubscribe on subscription

Handling Exceptions

There are 4 types of exception in python client library.

  • The exception of Python client library itself.
  • The exception of native library.
  • The exception of websocket
  • The exception of subscription.
  • The exception of other TDengine function modules.
Error TypeDescriptionSuggested Actions
InterfaceErrorthe native library is too old that it cannot support the functionplease check the TDengine client version
ConnectionErrorconnection errorplease check TDengine's status and the connection params
DatabaseErrordatabase errorplease upgrade Python client library to latest
OperationalErroroperation error
ProgrammingError
StatementErrorthe exception of stmt
ResultError
SchemalessErrorthe exception of stmt schemaless
TmqErrorthe exception of stmt tmq

It usually uses try-expect to handle exceptions in python. For exception handling, please refer to Python Errors and Exceptions Documentation.

All exceptions from the Python client library are thrown directly. Applications should handle these exceptions. For example:

import taos

try:
conn = taos.connect()
conn.execute("CREATE TABLE 123") # wrong sql
except taos.Error as e:
print(e)
print("exception class: ", e.__class__.__name__)
print("error number:", e.errno)
print("error message:", e.msg)
except BaseException as other:
print("exception occur")
print(other)

# output:
# [0x0216]: syntax error near 'Incomplete SQL statement'
# exception class: ProgrammingError
# error number: -2147483114
# error message: syntax error near 'Incomplete SQL statement'

view source code

TDengine DataType vs. Python DataType

TDengine currently supports timestamp, number, character, Boolean type, and the corresponding type conversion with Python is as follows:

TDengine DataTypePython DataType
TIMESTAMPdatetime
INTint
BIGINTint
FLOATfloat
DOUBLEint
SMALLINTint
TINYINTint
BOOLbool
BINARYstr
NCHARstr
JSONstr

Installation Steps

Pre-installation preparation

  1. Install Python. The recent taospy package requires Python 3.6.2+. The earlier versions of taospy require Python 3.7+. The taos-ws-py package requires Python 3.7+. If Python is not available on your system, refer to the Python BeginnersGuide to install it.
  2. Install pip. In most cases, the Python installer comes with the pip utility. If not, please refer to pip documentation to install it. If you use a native connection, you will also need to Install Client Driver. The client install package includes the TDengine client dynamic link library (libtaos.so or taos.dll) and the TDengine CLI.

Install via pip

Uninstalling an older version

If you have installed an older version of the Python client library, please uninstall it beforehand.

pip3 uninstall taos taospy
note

Earlier TDengine client software includes the Python client library. If the Python client library is installed from the client package's installation directory, the corresponding Python package name is taos. So the above uninstall command includes taos, and it doesn't matter if it doesn't exist.

To install taospy

Install the latest version of:

pip3 install taospy

You can also specify a specific version to install:

pip3 install taospy==2.3.0

Install taos-ws-py (Optional)

The taos-ws-py package provides the way to access TDengine via WebSocket.

Install taos-ws-py with taospy
pip3 install taospy[ws]
Install taos-ws-py only
pip3 install taos-ws-py

Verify

For REST connections, verifying that the taosrest module can be imported successfully can be done in the Python Interactive Shell by typing.

import taosrest
tip

If you have multiple versions of Python on your system, you may have various pip commands. Be sure to use the correct path for the pip command. Above, we installed the pip3 command, which rules out the possibility of using the pip corresponding to Python 2.x versions. However, if you have more than one version of Python 3.x on your system, you still need to check that the installation path is correct. The easiest way to verify this is to type pip3 install taospy again in the command, and it will print out the exact location of taospy, for example, on Windows.

C:\> pip3 install taospy
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Requirement already satisfied: taospy in c:\users\username\appdata\local\programs\python\python310\lib\site-packages (2.3.0)

Establishing a connection

Connectivity testing

Before establishing a connection with the client library, we recommend testing the connectivity of the local TDengine CLI to the TDengine cluster.

For REST connections, make sure the cluster and taosAdapter component, are running. This can be tested using the following curl command.

curl -u root:taosdata http://<FQDN>:<PORT>/rest/sql -d "select server_version()"

The FQDN above is the FQDN of the machine running taosAdapter, PORT is the port taosAdapter listening, default is 6041. If the test is successful, it will output the server version information, e.g.

{
"code": 0,
"column_meta": [
[
"server_version()",
"VARCHAR",
7
]
],
"data": [
[
"3.0.0.0"
]
],
"rows": 1
}

Specify the Host and Properties to get the connection

The following example code assumes that TDengine is installed locally and that the default configuration is used for both FQDN and serverPort.

from taosrest import connect, TaosRestConnection, TaosRestCursor

conn = connect(url="http://localhost:6041",
user="root",
password="taosdata",
timeout=30)

view source code

All arguments to the connect() function are optional keyword arguments. The following are the connection parameters specified.

  • url: The URL of taosAdapter REST service. The default is http://localhost:6041.
  • user: TDengine user name. The default is root.
  • password: TDengine user password. The default is taosdata.
  • timeout: HTTP request timeout. Enter a value in seconds. The default is socket._GLOBAL_DEFAULT_TIMEOUT. Usually, no configuration is needed.

Priority of configuration parameters

If the configuration parameters are duplicated in the parameters or client configuration file, the priority of the parameters, from highest to lowest, are as follows:

  1. Parameters in connect function.
  2. the configuration file taos.cfg of the TDengine client driver when using a native connection.

Usage examples

Create database and tables

import taosrest

conn = taosrest.connect(url="http://localhost:6041")

db = "power"

conn.execute(f"DROP DATABASE IF EXISTS {db}")
conn.execute(f"CREATE DATABASE {db}")

# create super table
conn.execute(
f"CREATE TABLE `{db}`.`meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
)

# create table
conn.execute(f"CREATE TABLE `{db}`.`d0` USING `{db}`.`meters` TAGS(0, 'Los Angles')")

conn.close()

view source code

Insert data

# rest insert data
sql = """
INSERT INTO
power.d1001 USING power.meters TAGS('California.SanFrancisco', 2)
VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000)
('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000)
power.d1002 USING power.meters TAGS('California.SanFrancisco', 3)
VALUES ('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)
power.d1003 USING power.meters TAGS('California.LosAngeles', 2)
VALUES ('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000) ('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000)
power.d1004 USING power.meters TAGS('California.LosAngeles', 3)
VALUES ('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000) ('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)
"""

inserted = conn.execute(sql)
assert inserted == 8

view source code

NOW is an internal function. The default is the current time of the client's computer. NOW + 1s represents the current time of the client plus 1 second, followed by the number representing the unit of time: a (milliseconds), s (seconds), m (minutes), h (hours), d (days), w (weeks), n (months), y (years).

Querying Data

The RestClient class is a direct wrapper for the REST API. It contains only a sql() method for executing arbitrary SQL statements and returning the result.

client = taosrest.RestClient("http://localhost:6041")
result = client.sql(f"SELECT * from {db}.meters")
print(result)

"""
output:
{'code': 0, 'column_meta': [['ts', 'TIMESTAMP', 8], ['current', 'FLOAT', 4], ['voltage', 'INT', 4], ['phase', 'FLOAT', 4], ['location', 'VARCHAR', 64], ['groupid', 'INT', 4]], 'data': [[datetime.datetime(2018, 10, 3, 14, 38, 5), 10.3, 219, 0.31, 'California.SanFrancisco', 2], [datetime.datetime(2018, 10, 3, 14, 38, 15), 12.6, 218, 0.33, 'California.SanFrancisco', 2], [datetime.datetime(2018, 10, 3, 14, 38, 16, 800000), 12.3, 221, 0.31, 'California.SanFrancisco', 2], [datetime.datetime(2018, 10, 3, 14, 38, 16, 650000), 10.3, 218, 0.25, 'California.SanFrancisco', 3], [datetime.datetime(2018, 10, 3, 14, 38, 5, 500000), 11.8, 221, 0.28, 'California.LosAngeles', 2], [datetime.datetime(2018, 10, 3, 14, 38, 16, 600000), 13.4, 223, 0.29, 'California.LosAngeles', 2], [datetime.datetime(2018, 10, 3, 14, 38, 5), 10.8, 223, 0.29, 'California.LosAngeles', 3], [datetime.datetime(2018, 10, 3, 14, 38, 6, 500000), 11.5, 221, 0.35, 'California.LosAngeles', 3]], 'rows': 8}
"""

view source code

For a more detailed description of the sql() method, please refer to RestClient.

Execute SQL with reqId

The reqId is very similar to TraceID in distributed tracing systems. In a distributed system, a request may need to pass through multiple services or modules to be completed. The reqId is used to identify and associate all related operations of this request, allowing us to track and understand the complete execution path of the request. Here are some primary usage of reqId:

  • Request Tracing: By associating the same reqId with all related operations of a request, we can trace the complete path of the request within the system.
  • Performance Analysis: By analyzing a request's reqId, we can understand the processing time of the request across various services or modules, thereby identifying performance bottlenecks.
  • Fault Diagnosis: When a request fails, we can identify the location of the issue by examining the reqId associated with that request.

If the user does not set a reqId, the client library will generate one randomly internally, but it is still recommended for the user to set it, as it can better associate with the user's request.

As the way to connect introduced above but add req_id argument.

result = client.sql(f"SELECT * from {db}.meters", req_id=1)

view source code

Writing data via parameter binding

The Python client library provides a parameter binding api for inserting data. Similar to most databases, TDengine currently only supports the question mark ? to indicate the parameters to be bound.

sql = "INSERT INTO ? USING meters TAGS(?,?) VALUES (?,?,?,?)"
stmt = conn.statement(sql)

tbname = "power.d1001"

tags = taos.new_bind_params(2)
tags[0].binary(["California.SanFrancisco"])
tags[1].int([2])

stmt.set_tbname_tags(tbname, tags)

params = taos.new_bind_params(4)
params[0].timestamp((1626861392589, 1626861392591, 1626861392592))
params[1].float((10.3, 12.6, 12.3))
params[2].int([194, 200, 201])
params[3].float([0.31, 0.33, 0.31])

stmt.bind_param_batch(params)

stmt.execute()

stmt.close()

view source code

Schemaless Writing

Client library support schemaless insert.

import taos

conn = taos.connect(
host="localhost",
user="root",
password="taosdata",
port=6030,
)

db = "power"

conn.execute(f"DROP DATABASE IF EXISTS {db}")
conn.execute(f"CREATE DATABASE {db}")

# change database. same as execute "USE db"
conn.select_db(db)

lineDemo = [
"meters,groupid=2,location=California.SanFrancisco current=10.3000002f64,voltage=219i32,phase=0.31f64 1626006833639000000"
]
telnetDemo = ["stb0_0 1707095283260 4 host=host0 interface=eth0"]
jsonDemo = [
'{"metric": "meter_current","timestamp": 1626846400,"value": 10.3, "tags": {"groupid": 2, "location": "California.SanFrancisco", "id": "d1001"}}'
]

conn.schemaless_insert(
lineDemo, taos.SmlProtocol.LINE_PROTOCOL, taos.SmlPrecision.MILLI_SECONDS
)
conn.schemaless_insert(
telnetDemo, taos.SmlProtocol.TELNET_PROTOCOL, taos.SmlPrecision.MICRO_SECONDS
)
conn.schemaless_insert(
jsonDemo, taos.SmlProtocol.JSON_PROTOCOL, taos.SmlPrecision.MILLI_SECONDS
)

conn.close()

view source code

Schemaless with reqId

There is a optional parameter called req_id in schemaless_insert and schemaless_insert_raw method. This reqId can be used to request link tracing.

conn.schemaless_insert(
lines=lineDemo,
protocol=taos.SmlProtocol.LINE_PROTOCOL,
precision=taos.SmlPrecision.NANO_SECONDS,
req_id=1,
)

Data Subscription

Client library support data subscription. For more information about subscroption, please refer to Data Subscription.

Create a Topic

# create topic
conn.execute(
f"CREATE TOPIC IF NOT EXISTS {topic} AS SELECT ts, current, voltage, phase, groupid, location FROM meters"
)

view source code

Create a Consumer

from taos.tmq import Consumer

consumer = Consumer(
{
"group.id": "1",
"td.connect.user": "root",
"td.connect.pass": "taosdata",
"enable.auto.commit": "true",
}
)

view source code

Subscribe to a Topic

consumer.subscribe([topic])

view source code

Consume messages

    while True:
res = consumer.poll(1)
if not res:
break
err = res.error()
if err is not None:
raise err
val = res.value()

for block in val:
print(block.fetchall())

view source code

Assignment subscription Offset

The assignment function is used to get the assignment of the topic.

    assignments = consumer.assignment()
for assignment in assignments:
print(assignment)

view source code

The seek function is used to reset the assignment of the topic.

    while True:
res = consumer.poll(1)
if not res:
break
err = res.error()
if err is not None:
raise err
val = res.value()

for block in val:
print(block.fetchall())

view source code

Close subscriptions

You should unsubscribe to the topics and close the consumer after consuming.

    consumer.unsubscribe()
consumer.close()

view source code

Full Sample Code

import taos

conn = taos.connect(
host="localhost",
user="root",
password="taosdata",
port=6030,
)

db = "power"
topic = "topic_meters"

conn.execute(f"DROP TOPIC IF EXISTS {topic}")
conn.execute(f"DROP DATABASE IF EXISTS {db}")
conn.execute(f"CREATE DATABASE {db}")

# change database. same as execute "USE db"
conn.select_db(db)

# create super table
conn.execute(
"CREATE STABLE power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)"
)

# 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

# ANCHOR: create_consumer
from taos.tmq import Consumer

consumer = Consumer(
{
"group.id": "1",
"td.connect.user": "root",
"td.connect.pass": "taosdata",
"enable.auto.commit": "true",
}
)
# ANCHOR_END: create_consumer

# ANCHOR: subscribe
consumer.subscribe([topic])
# ANCHOR_END: subscribe

try:
# ANCHOR: consume
while True:
res = consumer.poll(1)
if not res:
break
err = res.error()
if err is not None:
raise err
val = res.value()

for block in val:
print(block.fetchall())
# ANCHOR_END: consume

# ANCHOR: assignment
assignments = consumer.assignment()
for assignment in assignments:
print(assignment)
# ANCHOR_END: assignment

# ANCHOR: seek
offset = taos.tmq.TopicPartition(
topic=topic,
partition=assignment.partition,
offset=0,
)
consumer.seek(offset)
# ANCHOR_END: seek
finally:
# ANCHOR: unsubscribe
consumer.unsubscribe()
consumer.close()
# ANCHOR_END: unsubscribe

conn.close()

view source code

Other sample programs

Example program linksExample program content
bind_multi.pyparameter binding, bind multiple rows at once
bind_row.pyparameter binding, bind one row at once
insert_lines.pyInfluxDB line protocol writing
json_tag.pyUse JSON type tags
tmq_consumer.pyTMQ subscription

Other notes

About nanoseconds

Due to the current imperfection of Python's nanosecond support (see link below), the current implementation returns integers at nanosecond precision instead of the datetime type produced by ms and us, which application developers will need to handle on their own. And it is recommended to use pandas' to_datetime(). The Python client library may modify the interface in the future if Python officially supports nanoseconds in full.

  1. https://stackoverflow.com/questions/10611328/parsing-datetime-strings-containing-nanoseconds
  2. https://www.python.org/dev/peps/pep-0564/

API Reference

Frequently Asked Questions

Welcome to ask questions or report questions.