欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python 使用Python远程连接并操作InfluxDB数据库

程序员文章站 2022-04-28 12:44:57
使用Python远程连接并操作InfluxDB数据库 by:授客 QQ:1033553122 实践环境 Python 3.4.0 CentOS 6 64位(内核版本2.6.32-642.el6.x86_64) influxdb-1.5.2.x86_64.rpm 网盘下载地址: https://pan ......

使用python远程连接并操作influxdb数据库

by:授客 qq:1033553122

实践环境

python 3.4.0

 

centos 6 64位(内核版本2.6.32-642.el6.x86_64)

 

influxdb-1.5.2.x86_64.rpm

网盘下载地址:

https://pan.baidu.com/s/1jaby4xz5gvzoxxlhesq-pa

 

 

influxdb-5.0.0-py2.py3-none-any.whl

下载地址:

下载地址:https://pan.baidu.com/s/1dq0hgyng2a2-vnrsbdphmg

 

 

 

几个重要的名词介绍

database:数据库;

measurement:数据库中的表;

point:表里面的一行数据。

 

每个行记录由time(纳秒时间戳)、字段(fields)和tags组成。

time:每条数据记录的时间,也是数据库自动生成的主索引;

fields:记录各个字段的值;

tags:各种有索引的属性,一般用于where查询条件。

 

实践代码

#encoding:utf-8

__author__ = 'shouke'

 

import random

 

from influxdb import influxdbclient

 

 

client = influxdbclient('10.203.25.106', 8086, timeout=10) # timeout 超时时间 10秒

 

print('获取数据库列表:')

database_list = client.get_list_database()

print(database_list)

 

print('\n创建数据库')

client.create_database('mytestdb')

print(client.get_list_database())

 

print('\n切换至数据库(切换至对应数据库才可以操作数据库对象)\n')

client.switch_database('mytestdb')

 

print('插入表数据\n')

for i in range(0, 10):

    json_body = [

        {

            "measurement": "table1",

            "tags": {

                "stuid": "stuid1"

            },

            # "time": "2018-05-16t21:58:00z",

            "fields": {

                "value": float(random.randint(0, 1000))

            }

        }

    ]

    client.write_points(json_body)

 

print('查看数据库所有表\n')

tables = client.query('show measurements;')

 

print('查询表记录')

rows = client.query('select value from table1;')

print(rows)

 

print('\n删除表\n')

client.drop_measurement('table1')

 

print('删除数据库\n')

client.drop_database('mytestdb')

 

 

输出结果:

获取数据库列表:

[{'name': '_internal'}]

 

创建数据库

[{'name': '_internal'}, {'name': 'mytestdb'}]

 

切换至数据库(切换至对应数据库才可以操作数据库对象)

 

插入表数据

 

查看数据库所有表

 

查询表记录

resultset({'('table1', none)': [{'time': '2018-05-23t11:55:55.341839963z', 'value': 165}, {'time': '2018-05-23t11:55:55.3588771z', 'value': 215}, {'time': '2018-05-23t11:55:55.367430575z', 'value': 912}, {'time': '2018-05-23t11:55:55.37528554z', 'value': 34}, {'time': '2018-05-23t11:55:55.383530082z', 'value': 680}, {'time': '2018-05-23t11:55:55.391322174z', 'value': 247}, {'time': '2018-05-23t11:55:55.399173622z', 'value': 116}, {'time': '2018-05-23t11:55:55.407073805z', 'value': 224}, {'time': '2018-05-23t11:55:55.414792607z', 'value': 415}, {'time': '2018-05-23t11:55:55.422871017z', 'value': 644}]})

 

删除表

 

删除数据库

 

说明:

class influxdb.influxdbclient(host=u'localhost', port=8086, username=u'root', password=u'root', database=none, ssl=false, verify_ssl=false, timeout=none, retries=3, use_udp=false, udp_port=4444, proxies=none)

 

参数

host (str) – 用于连接的influxdb主机名称,默认‘localhost’

port (int) – 用于连接的influxport端口,默认8086

username (str) – 用于连接的用户名,默认‘root’

password (str) – 用户密码,默认‘root’

database (str) – 需要连接的数据库,默认none

ssl (bool) – 使用https连接,默认false

verify_ssl (bool) – 验证https请求的ssl证书,默认false

timeout (int) – 连接超时时间(单位:秒),默认none,

retries (int) – 终止前尝试次数(number of retries your client will try before aborting, defaults to 3. 0 indicates try until success)

use_udp (bool) – 使用udp连接到influxdb默认false

udp_port (int) – 使用udp端口连接,默认4444

proxies (dict) – 为请求使用http(s)代理,默认 {}

 

query(query, params=none, epoch=none, expected_response_code=200, database=none, raise_errors=true, chunked=false, chunk_size=0)

参数:

query (str) – 真正执行查询的字符串

params (dict) – 查询请求的额外参数,默认{}

epoch (str) – response timestamps to be in epoch format either ‘h’, ‘m’, ‘s’, ‘ms’, ‘u’, or ‘ns’,defaults to none which is rfc3339 utc format with nanosecond precision

expected_response_code (int) – 期望的响应状态码,默认 200

database (str) – 要查询的数据库,默认数据库

raise_errors (bool) – 查询返回错误时,是否抛出异常,默认

chunked (bool) – enable to use chunked responses from influxdb. with chunked enabled, one resultset is returned per chunk containing all results within that chunk

chunk_size (int) – size of each chunk to tell influxdb to use.

 

返回数据查询结果集

 

write_points(points, time_precision=none, database=none, retention_policy=none, tags=none, batch_size=none, protocol=u'json')

参数

points  由字典项组成的list,每个字典成员代表了一个

time_precision (str) – either ‘s’, ‘m’, ‘ms’ or ‘u’, defaults to none

database (str) – points需要写入的数据库,默认为当前数据库

tags (dict) – 同每个point关联的键值对,key和value都要是字符串.

retention_policy (str) – the retention policy for the points. defaults to none

batch_size (int) – value to write the points in batches instead of all at one time. useful for when doing data dumps from one database to another or when doing a massive write operation, defaults to none

protocol (str) – protocol for writing data. either ‘line’ or ‘json’.

如果操作成功,返回true

 

query,write_points操作来说,如果操作执行未调用switch_database函数,切换到目标数据库,可以在调用query,write_points函数时,可以指定要操作的数据库,如下

client.query('show measurements;', database='mytestdb')

client.write_points(json_body, database='mytestdb')

 

points参数值,可以不指定 time,这样采用influxdb自动生成的时间

    json_body = [

        {

            "measurement": "table1",

            "tags": {

                "stuid": "stuid1"

            },

            # "time": "2018-05-16t21:58:00z",

            "fields": {

                "value": float(random.randint(0, 1000))

            }

        }

    ]

 

另外,需要注意的是,influxdb使用utc时间,所以,如果显示指定时间,需要做如下处理:

timetuple = time.strptime(time.localtime(), '%y-%m-%d %h:%m:%s')

second_for_localtime_utc = int(time.mktime(timetuple)) + 1 - 8 * 3600 # utc时间(秒)

timetuple = time.localtime(second_for_localtime_utc)

date_for_data = time.strftime('%y-%m-%d', timetuple)

time_for_data = time.strftime('%h:%m:%s', timetuple)

datetime_for_data = date_for_data + 't' + time_for_data + 'z'

 

json_body = [

{

        "measurement": "table1",

        "tags": {

            "stuid": "stuid1"

        },

        "time": datetime_for_data,

        "fields": {

            "value": float(random.randint(0, 1000))

        }

   }

]