Connect with Python
Install Client Library
Preparation
You must first install Python3 and Pip3.
- Install Python. The newer versions of the taospy package require Python 3.6.2+. Earlier versions of the taospy package require Python 3.7+. The taos-ws-py package requires Python 3.7+. If Python is not yet installed on your system, you can refer to the Python Beginners Guide for installation.
- Install Pip3. In most cases, the Python installation package comes with the pip tool. If it's not included, please refer to the pip documentation for installation.
Install with Pip
If you have installed an older version of the Python connector, please uninstall it in advance.
- REST
- WebSocket
pip3 uninstall taos taospy
pip3 uninstall taos taos-ws-py
To install the latest or a specific version of taospy
or taos-ws-py
, execute the following command in the terminal.
- REST
- WebSocket
# install latest version
pip3 install taospy
# install specific version
pip3 install taospy==2.6.2
# install from github
pip3 install git+https://github.com/taosdata/taos-connector-python.git
pip3 install taos-ws-py
Verify
- REST
- WebSocket
For REST connections, simply verify that the taosrest
module can be successfully imported. You can enter the following in the Python interactive Shell:
import taosrest
For WebSocket connections, simply verify that the taosws
module can be successfully imported. You can enter the following in the Python interactive Shell:
import taosws
Config
Run this command in your terminal to save TDengine cloud token and URL as variables:
- Bash
- CMD
- Powershell
export TDENGINE_CLOUD_URL="<url>"
export TDENGINE_CLOUD_TOKEN="<token>"
set TDENGINE_CLOUD_URL=<url>
set TDENGINE_CLOUD_TOKEN=<token>
$env:TDENGINE_CLOUD_URL='<url>'
$env:TDENGINE_CLOUD_TOKEN='<token>'
Alternatively, you can also set environment variables in your IDE's run configurations.
Replace <token> and <url> with cloud token and URL.
To obtain the value of cloud token and URL, please login TDengine Cloud and click "Programming" on the left menu, then select "Python".
Please ensure to distinguish between the URLs for REST connections and WebSocket connections.
Connect
Copy code bellow to your editor, then run it.
- REST
- WebSocket
import taosrest
import os
url = os.environ["TDENGINE_CLOUD_URL"]
token = os.environ["TDENGINE_CLOUD_TOKEN"]
try:
conn = taosrest.connect(url=url, token=token)
# test the connection by getting version info
print("TDengine version: ", conn.server_info)
except Exception as e:
print(str(e))
import taosws
import os
url = os.environ["TDENGINE_CLOUD_URL"]
token = os.environ["TDENGINE_CLOUD_TOKEN"]
try:
conn = taosws.connect("%s?token=%s" % (url, token))
except Exception as e:
print(str(e))
For how to write data and query data, please refer to Insert and Query.
For more details about how to write or query data via REST API, please check REST API.