生活不易 我用python

prometheus数据生成报表输出到docx

2018-07-15  本文已影响3人  vonhng

1、环境需求:

npm install -g phantomjs-prebuilt
pip install pyecharts
pip install pyecharts-snapshot, jinja2

2、了解docx的结构

推荐阅读的文章:

  1. https://www.cnblogs.com/zhanghongfeng/p/7043412.html
  2. https://blog.csdn.net/qwe125698420/article/details/70622289?locationNum=3&fps=1

研究发现docx与xml关系密切,所以我们以xml为模板,最后从xml转换为docx文件

3、我的模板

使用docx文件创建模板,另存为xml文件

4、获取prometheus数据

url = "http://{host}:{port}/api/v1/query_range?query=ping_delay<peer='{peer}'," \
      "source='{source}'>&start={start_time}&end={end_time}&step=14"
      
end_time = time.time()
start_time = end_time - 3600

qyery_url = url.format(host="192.168.1.84", port="10011", peer="172.16.128.16",
                       source="10.10.90.11", start_time=start_time, end_time=end_time)
                       
status_url = qyery_url.replace("<", "{").replace(">", "}")

rsp = do_request(status_url)
if rsp.get("status", "") == "success" and rsp.get("data", {}).get("result", []):
    data = rsp["data"]["result"][0]["values"]

5、生成png图片

from pyecharts import Bar, Pie, Grid, Line, Overlap


def create_a_pic():
    attr = ["良好", "正常", "警告", "严重"]
    good, nomal, warn, cri = 0, 0, 0, 0
    y = [u'0.101', u'0.086', u'0.125',...]
    for i in y:
        i = float(i)
        if i >= 0.1:
            cri += 1
        elif 0.08 <= i < 0.1:
            warn += 1
        elif 0.04 < i < 0.08:
            nomal += 1
        else:
            good += 1

x = [1526968691.6, 1526968705.6, 1526968719.6,  ...]
    
pie = Pie("链路延迟等级分布图")
pie.add("delay", attr, [good, nomal, warn, cri], is_random=True, radius=[30, 75])
pie.render(path="test.png")

6、编译图片

def get_encoded_pic(path):
    """
    将图片转化为字节数据
    :param path: 图片的路径
    :return: 加密的字节数据
    """
    if not os.path.exists(path):
        raise Exception("{} not exists".format(path))
    with open(path, "rb") as f:
        data = base64.standard_b64encode(f.read())
        return data

7、生成xml文件

def writeback_xml(data):
    """
    :param data: 图片的字节数据
    :return: 
    """
    env = Environment(loader=FileSystemLoader(PWD))
    template = env.get_template("test.xml")
    with open(NEW_XML_PATH, "wb") as f:
        f.write(template.render(pic=data.decode("utf-8")).encode("utf-8"))
        
# data是编译图片生成的bytes格式的字符串
# data.decode("utf-8")将bytes解码成unicode
# render之后是str格式,但是f.write()需要unicode格式
# 所以使用encode("utf-8")

8、生成docx文件

将上面生成的xml文件另存为docx格式即可

上一篇下一篇

猜你喜欢

热点阅读