python.mdx 15.5 KB
Newer Older
D
dingbo 已提交
1 2 3 4 5 6 7 8 9 10
---
sidebar_position: 3
sidebar_label: Python
title: TDengine Python Connector
description: "taospy 是 TDengine 的官方 Python 连接器。taospy 提供了丰富的 API, 使得 Python 应用可以很方便地使用 TDengine。tasopy 对 TDengine 的原生接口和 REST 接口都进行了封装, 分别对应 tasopy 的两个子模块:tasos 和 taosrest。除了对原生接口和 REST 接口的封装,taospy 还提供了符合 Python 数据访问规范(PEP 249)的编程接口。这使得 taospy 和很多第三方工具集成变得简单,比如 SQLAlchemy 和 pandas"
---

import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";

11 12
`taospy` is the official Python connector for TDengine. `taospy` provides a rich API that makes it easy for Python applications to use TDengine. `taospy` wraps both the [native interface](/reference/connector/cpp) and [REST interface](/reference/rest-api) of TDengine, which correspond to the `taos` and `taosrest` modules of the `taospy` package, respectively.
In addition to wrapping the native and REST interfaces, `taospy` also provides a programming interface that conforms to the [Python Data Access Specification (PEP 249)](https://peps.python.org/pep-0249/). It is easy to integrate `taospy` with many third-party tools, such as [SQLAlchemy](https://www.sqlalchemy.org/) and [pandas](https://pandas.pydata.org/).
D
dingbo 已提交
13

14
The connection to the server directly 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 interface provided by taosAdapter is referred to hereinafter as a "REST connection". ".
D
dingbo 已提交
15

16
The source code for the Python connector is hosted on [GitHub](https://github.com/taosdata/taos-connector-python).
D
dingbo 已提交
17

18
## Supported Platforms
D
dingbo 已提交
19

20 21
- The native connection [supported platforms](/reference/connector/#supported-platforms) is the same as the one supported by the TDengine client.
- REST connections are supported on all platforms that can run Python.
D
dingbo 已提交
22

23
## Version selection
D
dingbo 已提交
24

25
We recommend using the latest version of `taospy`, regardless of the version of TDengine used.
D
dingbo 已提交
26

27
## Supported features
D
dingbo 已提交
28

29 30
- Native connections support all the core features of TDeingine, including connection management, SQL execution, parameter binding, 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.).
D
dingbo 已提交
31

32
## Installation
D
dingbo 已提交
33

34
### Preparation
D
dingbo 已提交
35

36 37 38
1. Install Python. Python >= 3.6 is recommended. If Python is not available on your system, refer to the [Python BeginnersGuide](https://wiki.python.org/moin/BeginnersGuide/Download) to install it. 2.
Install [pip](https://pypi.org/project/pip/). In most cases, the Python installer comes with the pip utility. If not, please refer to [pip docuemntation](https://pip.pypa.io/en/stable/installation/) to install it.
If you use a native connection, you will also need to [install the client driver](...). /#install client driver). The client software contains the TDengine client dynamic link library (libtaos.so or taos.dll) and the TDengine CLI.
D
dingbo 已提交
39

40
### Install using pip
D
dingbo 已提交
41

42
#### Uninstalling an older version
D
dingbo 已提交
43

44
If you have previously installed an older version of the Python Connector, please uninstall it beforehand.
D
dingbo 已提交
45 46 47 48 49 50

```
pip3 uninstall taos taospy
```

:::note
51
Earlier TDengine client software includes the Python connector. If the Python connector is installed from the client software'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.
D
dingbo 已提交
52 53 54

:::

55
#### to install `taospy`
D
dingbo 已提交
56 57

<Tabs>
58
<TabItem label="Install from PyPI" value="pypi">
D
dingbo 已提交
59

60
Install the latest version of
D
dingbo 已提交
61 62 63 64 65

```
pip3 install taospy
```

66
You can also specify a specific version to install.
D
dingbo 已提交
67 68 69 70 71

```
pip3 install taospy==2.3.0
```

72
</TabItem>
73
<TabItem label="Install from GitHub" value="github">
D
dingbo 已提交
74 75 76 77 78 79 80 81

```
pip3 install git+https://github.com/taosdata/taos-connector-python.git
```

</TabItem>
</Tabs>

82
### Installation verification
D
dingbo 已提交
83 84

<Tabs groupId="connect" default="native">
85
<TabItem value="native" label="native connection">
D
dingbo 已提交
86

87
For native connections, you need to verify that both the client driver and the Python connector itself are installed correctly. The client driver and Python connector have been installed properly if you can successfully import the `taos` module. In the Python Interactive Shell, you can type.
D
dingbo 已提交
88 89 90 91 92 93

```python
import taos
```

</TabItem>
94
<TabItem value="rest" label="REST connection">
D
dingbo 已提交
95

96
For REST connections, verifying that the ``taosrest`'' module can be imported successfully can be done in the Python Interactive Shell by typing.
D
dingbo 已提交
97 98 99 100 101 102 103 104 105

```python
import taosrest
```

</TabItem>
</Tabs>

:::tip
106
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.
D
dingbo 已提交
107 108 109 110 111

```
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)
112
ðŸ™'ðŸ™'
D
dingbo 已提交
113 114 115

:::

116
## Establish connection
D
dingbo 已提交
117

118
### Connectivity testing
D
dingbo 已提交
119

120
Before establishing a connection with the connector, we recommend testing the connectivity of the local TDengine CLI to the TDengine cluster.
D
dingbo 已提交
121

122
<Tabs>
123
<TabItem value="native" label="native connection">
D
dingbo 已提交
124

125
Ensure that the TDengine cluster is up and that the FQDN of the machines in the cluster (the FQDN defaults to hostname if you are starting a standalone version) can be resolved locally, by testing with the ping command.
D
dingbo 已提交
126 127 128 129 130

```
ping <FQDN>
```

131
Then test if the cluster can be appropriately connected with TDengine CLI: ``` ping <FQDN>```
D
dingbo 已提交
132 133 134 135 136

```
taos -h <FQDN> -p <PORT>
```

137
The FQDN above can be the FQDN of any dnode in the cluster, and the PORT is the serverPort corresponding to this dnode.
D
dingbo 已提交
138

139
</TabItem>
140
<TabItem value="rest" label="REST connection" groupId="connect">
D
dingbo 已提交
141

142
For REST connections and making sure the cluster is up, make sure the taosAdapter component is up. This can be tested using the following `curl ` command.
D
dingbo 已提交
143 144 145 146 147

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

148 149
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.
D
dingbo 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163

```json
{
  "status": "succ",
  "head": ["server_version()"],
  "column_meta": [["server_version()", 8, 8]],
  "data": [["2.4.0.16"]],
  "rows": 1
}
```

</TabItem>
</Tabs>

164
### Using connectors to establish connections
D
dingbo 已提交
165

166
The following example code assumes that TDengine is installed locally and that the default configuration is used for both FQDN and serverPort.
D
dingbo 已提交
167

168
<Tabs>
169
<TabItem value="native" label="native connection" groupId="connect">
D
dingbo 已提交
170 171 172 173 174

```python
{{#include docs-examples/python/connect_native_reference.py}}
```

175
All arguments of the ``connect`` function are optional keyword arguments. The following are the connection parameters specified.
D
dingbo 已提交
176

177 178 179 180 181 182
- `host` : The FQDN of the node to connect to. There is no default value. If this parameter is not provided, the firstEP in the client configuration file will be connected.
- `user` : The TDengine user name. The default value is `root`.
- `password` : TDengine user password. The default value is `taosdata`.
- `port` : The starting port of the data node to connect to, i.e., the serverPort configuration. The default value is 6030, which will only take effect if the host parameter is provided.
- `config` : The path to the client configuration file. On Windows systems, the default is `C:\TDengine\cfg`. The default is `/etc/taos/` on Linux systems.
- `timezone` : The timezone used to convert the TIMESTAMP data in the query results to python `datetime` objects. The default is the local timezone.
D
dingbo 已提交
183 184

:::warning
185
`config` and `timezone` are both process-level configurations. we recommend that all connections made by a process use the same parameter values. Otherwise, unpredictable errors may occur.
D
dingbo 已提交
186 187 188
:::

:::tip
189
The `connect` function returns a `taos.TaosConnection` instance. In client-side multi-threaded scenarios, we recommend that each thread request a separate connection instance rather than sharing a connection between multiple threads.
D
dingbo 已提交
190 191 192 193

:::

</TabItem>
194
<TabItem value="rest" label="REST connection">
D
dingbo 已提交
195 196 197 198 199

```python
{{#include docs-examples/python/connect_rest_examples.py:connect}}
```

200
All arguments to the `connect` function are optional keyword arguments. The following are the connection parameters specified.
D
dingbo 已提交
201

202 203 204 205 206
- `host`: The host to connect to. The default is localhost.
- `user`: TDenigne user name. The default is `root`.
- `password`: TDeingine user password. The default is `taosdata`.
- `port`: The port on which the taosAdapter REST service listens. Default is 6041.
- `timeout`: HTTP request timeout in seconds. The default is `socket._GLOBAL_DEFAULT_TIMEOUT`. Usually, no configuration is needed.
D
dingbo 已提交
207 208 209 210 211 212 213 214

:::note

:::

</TabItem>
</Tabs>

215
## Sample program
D
dingbo 已提交
216

217
### Basic use
D
dingbo 已提交
218 219

<Tabs default="native" groupId="connect">
220
<TabItem value="native" label="native connection">
D
dingbo 已提交
221

222
Use of the ##### TaosConnection class
D
dingbo 已提交
223

224
The `TaosConnection` class contains both an implementation of the PEP249 Connection interface (e.g., the `cursor` method and the `close` method) and many extensions (e.g., the `execute`, `query`, `schemaless_insert`, and `subscribe` methods). .
D
dingbo 已提交
225

226
```python title="execute method"
D
dingbo 已提交
227 228 229
{{#include docs-examples/python/connection_usage_native_reference.py:insert}}
```

230
```python title="query method"
D
dingbo 已提交
231 232 233 234
{{#include docs-examples/python/connection_usage_native_reference.py:query}}
```

:::tip
235
The queried results can only be fetched once. For example, only one of `featch_all` and `fetch_all_into_dict` can be used in the example above. Repeated fetches will result in an empty list.
D
dingbo 已提交
236 237
:::

238
##### Use of TaosResult class
D
dingbo 已提交
239

240
In the above example of using the `TaosConnection` class, we have shown two ways to get the result of a query: `featch_all` and `fetch_all_into_dict`. In addition, `TaosResult` also provides methods to iterate through the result set by rows (`rows_iter`) or by data blocks (`blocks_iter`). Using these two methods will be more efficient in scenarios where the query has a large amount of data.
D
dingbo 已提交
241

242
```python title="blocks_iter method"
D
dingbo 已提交
243 244
{{#include docs-examples/python/result_set_examples.py}}
```
245
##### Use of the TaosCursor class
D
dingbo 已提交
246

247
The `TaosConnection` class and the `TaosResult` class already implement all the functionality of the native interface. If you are familiar with the interfaces in the PEP249 specification, you can also use the methods provided by the `TaosCursor` class.
D
dingbo 已提交
248

249
```python title="Use of TaosCursor"
D
dingbo 已提交
250 251 252 253
{{#include docs-examples/python/cursor_usage_native_reference.py}}
```

:::note
254
The TaosCursor class uses native connections for write and query operations. In a client-side multi-threaded scenario, this cursor instance must remain thread exclusive and cannot be shared across threads for use, otherwise, it will result in errors in the returned results.
D
dingbo 已提交
255 256 257

:::

258
</TabItem>
259
<TabItem value="rest" label="REST connection">
D
dingbo 已提交
260

261
##### Use of TaosRestCursor class
D
dingbo 已提交
262

263
The ``TaosRestCursor`` class is an implementation of the PEP249 Cursor interface.
D
dingbo 已提交
264

265
```python title="Use of TaosRestCursor"
D
dingbo 已提交
266 267
{{#include docs-examples/python/connect_rest_examples.py:basic}}
```
268 269 270
- `cursor.execute` : Used to execute arbitrary SQL statements.
- `cursor.rowcount` : For write operations, returns the number of successful rows written. For query operations, returns the number of rows in the result set.
- `cursor.description` : Returns the description of the field. Please refer to [TaosRestCursor](https://docs.taosdata.com/api/taospy/taosrest/cursor.html) for the specific format of the description information.
D
dingbo 已提交
271

272
##### Use of the RestClient class
D
dingbo 已提交
273

274
The `RestClient` class is a direct wrapper for the [REST API](/reference/rest-api). It contains only a ``sql()` method for executing arbitrary SQL statements and returning the result.
D
dingbo 已提交
275

276
```python title="Use of RestClient"
D
dingbo 已提交
277 278 279
{{#include docs-examples/python/rest_client_example.py}}
```

280
For a more detailed description of the `sql()` method, please refer to [RestClient](https://docs.taosdata.com/api/taospy/taosrest/restclient.html).
D
dingbo 已提交
281 282 283 284

</TabItem>
</Tabs>

285
### Used with pandas
D
dingbo 已提交
286 287

<Tabs default="native" groupId="connect">
288
<TabItem value="native" label="native connection">
D
dingbo 已提交
289 290 291 292 293

```python
{{#include docs-examples/python/conn_native_pandas.py}}
```

294
</TabItem>
295
<TabItem value="rest" label="REST connection">
D
dingbo 已提交
296 297 298 299 300 301 302 303

```python
{{#include docs-examples/python/conn_rest_pandas.py}}
```

</TabItem>
</Tabs>

304
### Other sample programs
D
dingbo 已提交
305

306 307 308 309 310 311 312 313
| Example program links | Example program content |
| ------------------------------------------------------------------------------------------------------------- | ------------------- ---- |
| [bind_multi.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/bind-multi.py) | parameter binding, bind multiple rows at once |
| [bind_row.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/bind-row.py) | bind_row.py
| [insert_lines.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/insert-lines.py) | InfluxDB row protocol write |
| [json_tag.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/json-tag.py) | Use JSON type tags |
| [subscribe-async.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/subscribe-async.py) | Asynchronous subscription |
| [subscribe-sync.py](https://github.com/taosdata/taos-connector-python/blob/main/examples/subscribe-sync.py) | synchronous-subscribe |
D
dingbo 已提交
314

315
## Other notes 
D
dingbo 已提交
316

317
### Exception handling
D
dingbo 已提交
318

319
All database operations will be thrown directly if an exception occurs. The application is responsible for exception handling. For example:
D
dingbo 已提交
320 321 322 323 324

```python
{{#include docs-examples/python/handle_exception.py}}
```

325
### About nanoseconds
D
dingbo 已提交
326

327
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 Connector may modify the interface in the future if Python officially supports nanoseconds in full.
D
dingbo 已提交
328 329 330 331 332

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


333
## Frequently Asked Questions
D
dingbo 已提交
334

335
Welcome to [ask questions or report questions] (https://github.com/taosdata/taos-connector-python/issues).
D
dingbo 已提交
336

337
## Important Update
D
dingbo 已提交
338

339
| Connector version | Important Update | Release date |
D
dingbo 已提交
340 341 342 343 344
| ---------- | --------------------------------------------------------------------------------- | ---------- |
| 2.3.1      | 1. support TDengine REST API <br/> 2. remove support for Python version below 3.6 | 2022-04-28 |
| 2.2.5      | support timezone option when connect                                              | 2022-04-13 |
| 2.2.2      | support sqlalchemy dialect plugin                                                 | 2022-03-28 |

345
[**Release Notes**] (https://github.com/taosdata/taos-connector-python/releases)
D
dingbo 已提交
346

347
## API Reference
D
dingbo 已提交
348 349 350

- [taos](https://docs.taosdata.com/api/taospy/taos/)
- [taosrest](https://docs.taosdata.com/api/taospy/taosrest)