How to use Python to operate InfluxDB
To operate InfluxDB using Python, you need to install the Python library of InfluxDB. The installation command is as follows:
pip install influxdb
Then, you can use Python to operate InfluxDB for data addition, deletion, modification, and query operations according to the following example code.
1. Import the dependency library and create an InfluxDBClient connection:
python
from influxdb import InfluxDBClient
client = InfluxDBClient(host='localhost', port=8086, username='your_username', password='your_password', database='your_database')
2. Add data:
python
json_body = [
{
"measurement": "cpu_usage",
"tags": {
"host": "server01",
"region": "us-west"
},
"time": "2022-01-01T00:00:00Z",
"fields": {
"usage": 0.8
}
}
]
client.write_points(json_body)
3. Query data:
python
query = 'SELECT * FROM cpu_usage WHERE host = \'server01\''
result = client.query(query)
points = result.get_points()
for point in points:
print(f"Time: {point['time']}, Host: {point['host']}, Usage: {point['usage']}")
4. Update data:
python
query = "UPDATE cpu_usage SET usage = 0.6 WHERE host = 'server01'"
result = client.query(query)
5. Delete data:
python
query = "DELETE FROM cpu_usage WHERE host = 'server01'"
result = client.query(query)
This is a simple example code that you can modify and extend according to your own needs. Please note that the connection parameters in the example (such as host, username, password, database name) should be changed according to your actual environment.