0
# Core Client
1
2
The InfluxDBClient is the primary interface for interacting with InfluxDB servers. It provides comprehensive functionality for database operations, data querying and writing, connection management, and administrative tasks.
3
4
## Capabilities
5
6
### Client Initialization
7
8
Create and configure InfluxDB client connections with extensive customization options.
9
10
```python { .api }
11
class InfluxDBClient:
12
def __init__(self, host='localhost', port=8086, username='root', password='root',
13
database=None, ssl=False, verify_ssl=False, timeout=None, retries=3,
14
use_udp=False, udp_port=4444, proxies=None, pool_size=10, path='',
15
cert=None, gzip=False, session=None, headers=None, socket_options=None):
16
"""
17
Initialize InfluxDB client.
18
19
Parameters:
20
- host (str): Hostname (default: 'localhost')
21
- port (int): Port number (default: 8086)
22
- username (str): Username (default: 'root')
23
- password (str): Password (default: 'root')
24
- database (str): Database name (default: None)
25
- ssl (bool): Use SSL (default: False)
26
- verify_ssl (bool): Verify SSL certificates (default: False)
27
- timeout (int): Request timeout in seconds (default: None)
28
- retries (int): Number of retries (default: 3)
29
- use_udp (bool): Use UDP for writes (default: False)
30
- udp_port (int): UDP port (default: 4444)
31
- proxies (dict): HTTP proxies (default: None)
32
- pool_size (int): Connection pool size (default: 10)
33
- path (str): URL path prefix (default: '')
34
- cert (str): Client certificate path (default: None)
35
- gzip (bool): Use gzip compression (default: False)
36
- session (requests.Session): Custom HTTP session (default: None)
37
- headers (dict): Custom HTTP headers (default: None)
38
- socket_options (list): Socket options (default: None)
39
"""
40
41
@classmethod
42
def from_dsn(cls, dsn, **kwargs):
43
"""
44
Create client from data source name (DSN).
45
46
Parameters:
47
- dsn (str): Data source name URL
48
- **kwargs: Additional client parameters
49
50
Returns:
51
InfluxDBClient instance
52
"""
53
```
54
55
#### Usage Examples
56
57
```python
58
# Basic connection
59
client = InfluxDBClient()
60
61
# Production configuration
62
client = InfluxDBClient(
63
host='influxdb.example.com',
64
port=8086,
65
username='myuser',
66
password='mypass',
67
database='production',
68
ssl=True,
69
verify_ssl=True,
70
timeout=30,
71
retries=5,
72
pool_size=20
73
)
74
75
# DSN connection
76
client = InfluxDBClient.from_dsn('https://user:pass@influxdb.example.com:8086/mydb')
77
```
78
79
### Connection Management
80
81
Manage client connections and authentication dynamically.
82
83
```python { .api }
84
def ping(self):
85
"""
86
Check connectivity to InfluxDB server.
87
88
Returns:
89
dict: Server response with version information
90
91
Raises:
92
InfluxDBClientError: If connection fails
93
"""
94
95
def switch_database(self, database):
96
"""
97
Change the client's default database.
98
99
Parameters:
100
- database (str): Database name to switch to
101
"""
102
103
def switch_user(self, username, password):
104
"""
105
Change the client's authentication credentials.
106
107
Parameters:
108
- username (str): New username
109
- password (str): New password
110
"""
111
112
def close(self):
113
"""
114
Close the HTTP session and release resources.
115
"""
116
```
117
118
### Core Data Operations
119
120
Execute queries and write data to InfluxDB with flexible options.
121
122
```python { .api }
123
def query(self, query, params=None, bind_params=None, epoch=None,
124
expected_response_code=200, database=None, raise_errors=True,
125
chunked=False, chunk_size=0, method="GET"):
126
"""
127
Send query to InfluxDB and return results.
128
129
Parameters:
130
- query (str): InfluxQL query string
131
- params (dict): URL parameters (default: None)
132
- bind_params (dict): Query parameter bindings (default: None)
133
- epoch (str): Time precision ('s', 'ms', 'u', 'ns') (default: None)
134
- expected_response_code (int): Expected HTTP status (default: 200)
135
- database (str): Database name override (default: None)
136
- raise_errors (bool): Raise exceptions on query errors (default: True)
137
- chunked (bool): Enable chunked responses (default: False)
138
- chunk_size (int): Chunk size for chunked responses (default: 0)
139
- method (str): HTTP method ('GET' or 'POST') (default: 'GET')
140
141
Returns:
142
ResultSet: Query results wrapper
143
144
Raises:
145
InfluxDBClientError: On client errors
146
InfluxDBServerError: On server errors
147
"""
148
149
def write_points(self, points, time_precision=None, database=None,
150
retention_policy=None, tags=None, batch_size=None,
151
protocol='json', consistency=None):
152
"""
153
Write multiple time series points to InfluxDB.
154
155
Parameters:
156
- points (list): List of point dictionaries
157
- time_precision (str): Time precision ('s', 'ms', 'u', 'ns') (default: None)
158
- database (str): Database name override (default: None)
159
- retention_policy (str): Retention policy name (default: None)
160
- tags (dict): Global tags to add to all points (default: None)
161
- batch_size (int): Points per batch for large writes (default: None)
162
- protocol (str): Write protocol ('json' or 'line') (default: 'json')
163
- consistency (str): Write consistency level (default: None)
164
165
Returns:
166
bool: True if successful
167
168
Raises:
169
InfluxDBClientError: On write errors
170
"""
171
172
def write(self, data, params=None, expected_response_code=204, protocol='json'):
173
"""
174
Low-level write method for raw data.
175
176
Parameters:
177
- data (str or dict): Data to write
178
- params (dict): URL parameters (default: None)
179
- expected_response_code (int): Expected HTTP status (default: 204)
180
- protocol (str): Write protocol (default: 'json')
181
182
Returns:
183
bool: True if successful
184
"""
185
```
186
187
#### Query Examples
188
189
```python
190
# Simple query
191
result = client.query('SELECT * FROM cpu_usage')
192
193
# Query with time range
194
result = client.query("""
195
SELECT mean(value) as avg_cpu
196
FROM cpu_usage
197
WHERE time >= now() - 1h
198
GROUP BY time(10m)
199
""")
200
201
# Parameterized query
202
result = client.query(
203
'SELECT * FROM measurement WHERE host = $host',
204
bind_params={'host': 'server01'}
205
)
206
207
# Chunked query for large results
208
result = client.query(
209
'SELECT * FROM large_measurement',
210
chunked=True,
211
chunk_size=10000
212
)
213
```
214
215
#### Write Examples
216
217
```python
218
# Write single point
219
json_body = [
220
{
221
"measurement": "cpu_load_short",
222
"tags": {
223
"host": "server01",
224
"region": "us-west"
225
},
226
"time": "2023-09-07T07:18:24Z",
227
"fields": {
228
"value": 0.64
229
}
230
}
231
]
232
client.write_points(json_body)
233
234
# Write multiple points with global tags
235
points = [
236
{
237
"measurement": "temperature",
238
"fields": {"value": 23.5},
239
"time": "2023-09-07T07:18:24Z"
240
},
241
{
242
"measurement": "temperature",
243
"fields": {"value": 24.1},
244
"time": "2023-09-07T07:19:24Z"
245
}
246
]
247
client.write_points(points, tags={"location": "room1"})
248
249
# Write with line protocol
250
client.write_points(points, protocol='line')
251
252
# Batch write for large datasets
253
large_points = [...] # Many points
254
client.write_points(large_points, batch_size=5000)
255
```
256
257
### HTTP Request Interface
258
259
Direct access to InfluxDB HTTP API for advanced operations.
260
261
```python { .api }
262
def request(self, url, method='GET', params=None, data=None, stream=False,
263
expected_response_code=200, headers=None):
264
"""
265
Make direct HTTP request to InfluxDB API.
266
267
Parameters:
268
- url (str): API endpoint URL
269
- method (str): HTTP method (default: 'GET')
270
- params (dict): URL parameters (default: None)
271
- data (str or dict): Request body data (default: None)
272
- stream (bool): Stream response (default: False)
273
- expected_response_code (int): Expected HTTP status (default: 200)
274
- headers (dict): Additional HTTP headers (default: None)
275
276
Returns:
277
requests.Response: HTTP response object
278
279
Raises:
280
InfluxDBClientError: On request errors
281
"""
282
```
283
284
### UDP Operations
285
286
High-throughput data writing using UDP protocol.
287
288
```python { .api }
289
def send_packet(self, packet, protocol='json', time_precision=None):
290
"""
291
Send data packet via UDP for high-throughput writes.
292
293
Parameters:
294
- packet (str or dict): Data packet to send
295
- protocol (str): Packet protocol ('json' or 'line') (default: 'json')
296
- time_precision (str): Time precision ('s', 'ms', 'u', 'ns') (default: None)
297
298
Note: UDP writes are fire-and-forget with no error handling
299
"""
300
```
301
302
#### UDP Usage
303
304
```python
305
# Configure client for UDP
306
client = InfluxDBClient(use_udp=True, udp_port=4444)
307
308
# Send UDP packets
309
packet = {
310
"measurement": "cpu_load_short",
311
"tags": {"host": "server01"},
312
"fields": {"value": 0.64}
313
}
314
client.send_packet(packet)
315
316
# Line protocol UDP
317
line_data = "cpu_load_short,host=server01 value=0.64"
318
client.send_packet(line_data, protocol='line')
319
```
320
321
### Context Manager Support
322
323
Automatic resource management using Python context managers.
324
325
```python { .api }
326
def __enter__(self):
327
"""Enter context manager."""
328
return self
329
330
def __exit__(self, _exc_type, _exc_value, _traceback):
331
"""Exit context manager and clean up resources."""
332
```
333
334
#### Context Manager Usage
335
336
```python
337
# Automatic cleanup
338
with InfluxDBClient(host='localhost', database='mydb') as client:
339
client.write_points([{"measurement": "test", "fields": {"value": 1}}])
340
results = client.query('SELECT * FROM test')
341
# Client automatically closed when exiting context
342
```
343
344
## Configuration Examples
345
346
### SSL/TLS Setup
347
348
```python
349
client = InfluxDBClient(
350
host='secure.influxdb.com',
351
port=8086,
352
ssl=True,
353
verify_ssl=True,
354
cert='/path/to/client.pem'
355
)
356
```
357
358
### Proxy Configuration
359
360
```python
361
client = InfluxDBClient(
362
host='influxdb.internal.com',
363
proxies={
364
'http': 'http://proxy.company.com:8080',
365
'https': 'https://proxy.company.com:8080'
366
}
367
)
368
```
369
370
### Custom Headers and Authentication
371
372
```python
373
client = InfluxDBClient(
374
host='influxdb.com',
375
headers={
376
'Authorization': 'Bearer your-jwt-token',
377
'Custom-Header': 'value'
378
}
379
)
380
```