使用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://pypi.org/project/influxdb/#files

下载地址: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))

}

}

]

 

https://influxdb-python.readthedocs.io/en/latest/api-documentation.html#influxdbclient

Python 使用Python远程连接并操作InfluxDB数据库的更多相关文章

  1. Java java jdbc thin远程连接并操作Oracle数据库

    JAVA jdbc thin远程连接并操作Oracle数据库 by:授客 QQ:1033553122 测试环境 数据库:linux 下Oracle_11g_R2 编码工具:Eclipse 编码平台:W ...

  2. 远程连接ejabberd的mnesia数据库

    由于服务器是server版本,所以很难直观的看到mnesia的数据.所以对于初学者来说非常的困惑. 特地在qq群中请教了别人.别人说只要pong通了就行,就能通过rpc去操作远程的mnesia数据库. ...

  3. Java连接并操作SQLServer数据库

    本人只需在项目中引入sqljdbc4.jar 包即可 ----------------------------------------- 在JAVA中如何连接SQL Server数据库 - hangh ...

  4. 远程连接云主机MySql数据库

    笔者最近在学习MySql数据库,试着远程连接阿里云主机数据库.在连接过程中遇到不少麻烦,这里总结一下过程中遇到的问题. 基本前提 先在本地电脑和远程主机上安装MySql数据库,保证数据库服务启动. 云 ...

  5. 寝室远程连接室友mysql数据库

    注意,本方法是适用于同一局域网下的远程连接 注意,本方法是适用于同一局域网下的远程连接 注意,本方法是适用于同一局域网下的远程连接 首先需要修改mysql数据库的相关配置,将user表中的host改为 ...

  6. robot_framewok自动化测试--(9)连接并操作 MySql 数据库

    连接并操作 MySql 数据库 1.mysql数据库 1.1安装mysql数据库 请参考我的另一篇文章:MYSQL5.7下载安装图文教程 1.2.准备测试数据 请参考我的另一篇文章:Mysql基础教程 ...

  7. python连接,操作 InfluxDB

    准备工作 启动服务器 执行如下命令: service influxdb start 示例如下: [root@localhost ~]# service influxdb start Starting ...

  8. python 在window 系统 连接并操作远程 oracle 数据库

    1,python 连接 oracle 需要 oracle 自身的客户端  instantclient,可以去官网下载自己需要的版本, https://www.oracle.com/technetwor ...

  9. python接口自动化测试框架实现之操作oracle数据库

    python操作oracle数据库需要使用到cx-oracle库. 安装:pip install cx-oracle python连接oracle数据库分以下步骤: 1.与oracle建立连接: 2. ...

随机推荐

  1. Android OpenGL ES 开发(五): OpenGL ES 使用投影和相机视图

    OpenGL ES环境允许你以更接近于你眼睛看到的物理对象的方式来显示你绘制的对象.物理查看的模拟是通过对你所绘制的对象的坐标进行数学变换完成的: Projection - 这个变换是基于他们所显示的 ...

  2. [Swift]LeetCode478. 在圆内随机生成点 | Generate Random Point in a Circle

    Given the radius and x-y positions of the center of a circle, write a function randPoint which gener ...

  3. Netty:ChannelInitializer

    1. 作用 用于在某个Channel注册到EventLoop后,对这个Channel执行一些初始化操作.ChannelInitializer虽然会在一开始会被注册到Channel相关的pipeline ...

  4. RabbitMQ 学习笔记

    环境: MacOS 10.14 Node.js 8.9.1 零.背景 目前有个上线应用会接受多个请求,且每个请求的处理时间可能很久,可能到数小时,所以就想采用异步机制,至于复杂的运算就用消息队列(MQ ...

  5. SpringBoot 集成Mybatis 连接Mysql数据库

    记录SpringBoot 集成Mybatis 连接数据库 防止后面忘记 1.添加Mybatis和Mysql依赖 <dependency> <groupId>org.mybati ...

  6. 【Docker】(1)---Docker入门篇

    Docker入门篇 简单一句话: Docker 是一个便携的应用容器. 一.Docker的作用 网上铺天盖地的是这么说的: (1) Docker 容器的启动可以在秒级实现,这相比传统的虚拟机方式要快得 ...

  7. 『扩展欧几里得算法 Extended Euclid』

    Euclid算法(gcd) 在学习扩展欧几里得算法之前,当然要复习一下欧几里得算法啦. 众所周知,欧几里得算法又称gcd算法,辗转相除法,可以在\(O(log_2b)\)时间内求解\((a,b)\)( ...

  8. UPC:ABS

    问题 G: ABS 时间限制: 1 Sec  内存限制: 128 MB提交: 537  解决: 186[提交] [状态] [讨论版] [命题人:admin] 题目描述 We have a deck c ...

  9. HBase查询优化

    1.概述 HBase是一个实时的非关系型数据库,用来存储海量数据.但是,在实际使用场景中,在使用HBase API查询HBase中的数据时,有时会发现数据查询会很慢.本篇博客将从客户端优化和服务端优化 ...

  10. 【ASP.NET Core快速入门】(八)Middleware管道介绍、自己动手构建RequestDelegate管道

    中间件是汇集到以处理请求和响应的一个应用程序管道的软件. 每个组件: 可以选择是否要将请求传递到管道中的下一个组件. 之前和之后调用管道中的下一个组件,可以执行工作. 使用请求委托来生成请求管道. 请 ...