参考资料:
pymysql 单独获取表的栏位名称
pymysql返回数据为字典形式(key:value--列:值)
行列结合,作为prometheus_client的输出。 话不多说,直接上脚本。
cat mysql_ccpay.py
#coding=utf-8
import sys
import pymysql
import os
from prometheus_client import Gauge,start_http_server
import time
#v_host=os.popen('echo $HOSTNAME')
#hostname=v_host.read()
#hstname="".join(hostname)
#print(hostname.strip())
class MySQL_Status_Output:
    def __init__(self,host,port,user,password):
        try:
            self.db = pymysql.connect(host=host,port=port,user=user,password=password)
        except Exception as e:
            print('Database Connection Error')
            print(e)
    def mysql_select_colum_sql(self,sql):
        try:
            self.cursor = self.db.cursor(cursor = pymysql.cursors.DictCursor)
            self.cursor.execute(sql)
            v_result=self.cursor.fetchall()
            return v_result
        except Exception as e:
            print('SQL Result One Column Error')
            print(e)
    def mysql_select_sql(self,sql):
        try:
            self.cursor = self.db.cursor()
            self.cursor.execute(sql)
            col=self.cursor.description
            v_result=self.cursor.fetchall()
            return v_result,col
        except Exception as e:
            print('SQL Result More Column Error')
            print(e)
    def close_db(self):
        self.db.close()
def ccpay_sql_one_exec(sql_exec):
    try:
        pro_db = MySQL_Status_Output('127.0.0.1',3306,'dbadmin','dbadmin')
        ccpay_sql = pro_db.mysql_select_colum_sql(sql_exec)
        pro_db.close_db()
        #print('输出行数为:',len(ccpay_sql))
        if int(len(ccpay_sql))==1:
            for i in range(len(ccpay_sql)):
                c=ccpay_sql[i]
                a=list(c.keys())
                for j in range(len(a)):
                    print(a[j],':',c.get(a[j]))
                    ccpayGauge.labels(mylabelname=a[j]).set(c.get(a[j]))
        else:
            pass
    except Exception as e:
        print('One Colum ccpayGauge Error')
        print(e)
def ccpay_sql_more_exec(sql_exec):
    try:
        pro_db = MySQL_Status_Output('127.0.0.1',3306,'dbadmin','dbadmin')
        ccpay_sql,col_name = pro_db.mysql_select_sql(sql_exec)
        if int(len(ccpay_sql))>1:
            bs_name=[]
            for i in range(len(ccpay_sql)):
                bs_name.append(ccpay_sql[i][0])
            print(bs_name)
            for bsname in range(len(bs_name)):
                col_name_list=[]
                for i in range(len(col_name)):
                    col_name_list.append(col_name[i][0])
                col_name_tuple=tuple(col_name_list)
                ccpay_value_list=[]
                for j in range(len(ccpay_sql)):
                    if ccpay_sql[j][0]==bs_name[bsname]:
                        ccpay_value_list=ccpay_sql[j]
                        me=dict(zip(col_name_tuple,ccpay_value_list))
                        for key in me:
                            bn=str(bs_name[bsname]+key)
                            bkey=str(me[key])
                            if str(bs_name[bsname])==str(bkey):
                                #print(bs_name[bsname])
                                pass
                            else:
                                print(bn,':',bkey)
                                ccpayGauge.labels(mylabelname=bn).set(bkey)
    except Exception as e:
        print('More Colums ccpayGauge Error')
        print(e)

if __name__ == "__main__":
    start_http_server(9500)
    ccpayGauge = Gauge('ccpayGauge','Description of gauge', ['mylabelname'])
    while True:
        time.sleep(60)
        try:
            ccpay_sql_one_exec(" select count(1) '全盘交易笔数',count(case when trade_status !='FAILED' then 1 else null end) '全盘出码成功',count(case when trade_status ='SUCCESS' then 1 else null end) '全盘交易成功',count(case when notify_status ='SUCCESS' then 1 else null end) '全盘通知成功',sum(case when  trade_status ='SUCCESS' then TRADE_AMOUNT else null end)/100 '全盘成功金额',count(case when trade_status ='FAILED' and trade_errmsg = '指定设备无响应' then 1 else null end) '指定设备无响应',count(case when trade_status ='FAILED' and trade_errmsg = '找不到可用的设备' then 1 else null end) '找不到可用的设备',TRUNCATE(count(case when trade_status ='SUCCESS' then 1 else null end)*100/count(1),2) '全盘交易成功率' from ifpay_ccpay.trade_info where CREATE_TIME > curdate() ")
            ccpay_sql_one_exec(" select count(1) '可用设备' from ifpay_ccpay.machine where ENABLE_STATUS = '1' ")
            ccpay_sql_one_exec(" select count(distinct qrcode_url.qrcode_num) '新生码交易成功笔数' from ifpay_ccpay.trade_info inner join ifpay_ccpay.qrcode_url on trade_info.qrcode_num=qrcode_url.qrcode_num where trade_status='SUCCESS' and date(trade_info.create_time)=date(current_date()) and date(trade_info.create_time)=date(qrcode_url.created_date) ")
            ccpay_sql_more_exec(" select MERCHANT_name '商户名称',total '交易笔数',qrcode '出码成功',success '交易成功',notify '通知成功',(case when amount is null then 0 else amount end) '成功金额' from (select a.MERCHANT_name MERCHANT_name,count(1) total,count(case when trade_status !='FAILED' then 1 else null end) qrcode,count(case when trade_status ='SUCCESS' then 1 else null end) success,count(case when notify_status ='SUCCESS' then 1 else null end) notify,sum(case when  trade_status ='SUCCESS' then TRADE_AMOUNT else null end)/100 amount from ifpay_ccpay.trade_info,ifpay_ccpay.merchant a where MERCHANT_NO=a.MERCHANT_id  and CREATE_TIME > curdate() group by a.MERCHANT_name) a ")
        except Exception as e:
            print('Is Wrong')
            print(e)

输出结果:
Grafana输出

转载于:https://www.cnblogs.com/xibuhaohao/p/10032594.html

Python3.5+SQL+Prometheus+Grafana报表/监控相关推荐

  1. 视频教程-Prometheus+Grafana企业级监控实战(运维篇)2020年视频教程-Linux

    Prometheus+Grafana企业级监控实战(运维篇)2020年视频教程 资深DevOps工程师,曾经在华为,乐逗游戏工作,目前就职于知名物流公司工作 希望结合工作实践 给大家带来很多干货 周龙 ...

  2. 五分钟搭建基于 Prometheus + Grafana 实时监控系统

    文章目录 Prometheus + Grafana 实时监控系统 Prometheus + Grafana 实时监控系统 依赖镜像包 启动 node-exporter check 端口 node_ex ...

  3. 基于Prometheus+Grafana搭建监控平台-(2)实现监控elink服务器EIMServer

    EIMServer是由北京华夏易联科技开发有限公司研发的一款可以私有部署的即时通讯服务平台E-Link,服务器是基于OSGI框架研发的java服务器程序,所以也可以通过Prometheus+Grafa ...

  4. 基于Prometheus+Grafana搭建监控平台-(5)实现监控Solr服务

    基于Prometheus+Grafana搭建监控平台-(1)搭建基础环境,实现监控JVM 基于Prometheus+Grafana搭建监控平台-(2)实现监控elink服务器EIMServer 基于P ...

  5. Prometheus+Grafana PG监控部署以及自定义监控指标

    点击上方"蓝字" 关注我们,享更多干货! 1.前言 Prometheus:是从云原生计算基金会(CNCF)毕业的项目.Prometheus是Google监控系统BorgMon类似实 ...

  6. k8s实战之部署Prometheus+Grafana可视化监控告警平台

    写在前面 之前部署web网站的时候,架构图中有一环节是监控部分,并且搭建一套有效的监控平台对于运维来说非常之重要,只有这样才能更有效率的保证我们的服务器和服务的稳定运行,常见的开源监控软件有好几种,如 ...

  7. Jmeter+Prometheus+Grafana性能监控平台:将JMeter压测数据输出到Prometheus

    前言 1.小编之前写过一篇文章详细讲解了如何搭建一个HTTP接口性能实时监控测试平台,是用Grafana+Influxdb+Jmeter组合实现的,可以参考我写的这篇博客https://editor. ...

  8. Prometheus Grafana 搭建监控系统

    之前在业务中遇到服务器负载过高问题,由于没有监控,一直没发现,直到业务方反馈网站打开速度慢,才发现问题.这样显得开发很被动.所以是时候搭建一套监控系统了. 由于是业余时间自己捯饬,所以神马业务层面的监 ...

  9. docker实现locust+prometheus+grafana性能测试监控

    1. Locust + Prometheus + Grafana 简单总结起来就是:实现一个Locust的prometheus的exporter,将数据导入prometheus,然后使用grafana ...

最新文章

  1. Tomcat中容器的pipeline机制
  2. 快速高效计算sin与cos
  3. MongoDB入门(一)——数据库概述
  4. linux卸载htop,linux下 htop 工具简介
  5. 4g模块注册上网 移远_物联网模组龙头移远通信
  6. JS闭包中未使用的引用变量回收机制浅探
  7. SQL:一条SQL的查询结果作为另一条SQL的查询条件
  8. win10无法装载iso文件_教你用win10自带虚拟光驱打开iso镜像文件的方法
  9. 人工智能—产生式系统(专家系统)
  10. Mindjet MindManager2022思维导图解压安装程序教程
  11. 设计方面的优秀网站推荐QWQ
  12. 计算机应用参考文献,计算机应用领域英文参考文献 哪里有计算机应用领域参考文献...
  13. SIM7600X常用指令
  14. Java服务端集成支付宝支付SDK
  15. Eclips运行时概述4
  16. 导出excel文件后,显示文件损坏
  17. python获取2020年国家统计局省市县三级数据
  18. 18000-6c协议阅读笔记
  19. MySQL数据库怎么查看er图表_详解 Navicat 查看方式之ER图表
  20. 不走寻常路,一个程序媛十三年的野蛮生长

热门文章

  1. Facebook加入AI芯片大战,挖走Google芯片产品开发负责人
  2. Spring Boot + Vue 如此强大?
  3. 漫画 | 如果程序员的妈是产品经理,她会如何逼你结婚?
  4. Redis低成本高可用方案设计
  5. 你真的会写单例模式吗?
  6. 跟我学Springboot开发后端管理系统6:缓存框架Caffeine
  7. 如何把近十页的论文读成半页?
  8. 数据清洗指南完整分享
  9. Meta元宇宙OS要黄?300人研发团队解散,关闭VR/AR操作系统研发
  10. 你对象怎么找的?日本网友:国家用AI给分配的