首页 > 编程语言 >Prometheus Python client library.

Prometheus Python client library.

时间:2023-12-19 23:22:06浏览次数:41  
标签:__ Python self labels share Prometheus client sb

Prometheus Python client library.

http://prometheus.github.io/client_python/

 

Example

https://pbrissaud.github.io/suivi-bourse/

用户场景没有价值,此项目以全栈的视角实现了自定义exporter的实现,可以直接参考。

watches your stock share on Prometheus / Grafana

 

https://github.com/fanqingsong/suivi-bourse

"""
SuiviBourse
Paul Brissaud
"""
import os
import sys
from pathlib import Path
import random
import prometheus_client
import yaml
import yfinance as yf
from apscheduler.schedulers.blocking import BlockingScheduler
from cerberus import Validator
from confuse import Configuration
from logfmt_logger import getLogger
from urllib3 import exceptions as u_exceptions

app_logger = getLogger(
    "suivi_bourse", level=os.getenv('LOG_LEVEL', default='INFO'))
scheduler_logger = getLogger(
    "apscheduler.scheduler", level=os.getenv('LOG_LEVEL', default='INFO'))
yfinance_logger = getLogger(
    "yfinance", level=os.getenv('LOG_LEVEL', default='INFO'))


class InvalidConfigFile(Exception):
    def __init__(self, errors_):
        self.errors = errors_
        self.message = 'Shares field of the config file is invalid :' + \
            str(self.errors)
        super().__init__(self.message)


class SuiviBourseMetrics:
    def __init__(self, configuration_: Configuration, validator_: Validator):
        self.configuration = configuration_
        self.validator = validator_
        self.init_metrics()

    def init_metrics(self):
        if self.validate():
            common_labels = ['share_name', 'share_symbol']

            self.sb_random_variable = prometheus_client.Gauge(
                "sb_random_variable",
                "sb random variable",
                common_labels
            )

            self.sb_share_price = prometheus_client.Gauge(
                "sb_share_price",
                "Price of the share",
                common_labels
            )

            self.sb_purchased_quantity = prometheus_client.Gauge(
                "sb_purchased_quantity",
                "Quantity of purchased share",
                common_labels
            )

            self.sb_purchased_price = prometheus_client.Gauge(
                "sb_purchased_price",
                "Price of purchased share",
                common_labels
            )

            self.sb_purchased_fee = prometheus_client.Gauge(
                "sb_purchased_fee",
                "Fees",
                common_labels
            )

            self.sb_owned_quantity = prometheus_client.Gauge(
                "sb_owned_quantity",
                "Owned quantity of the share",
                common_labels
            )

            self.sb_received_dividend = prometheus_client.Gauge(
                "sb_received_dividend",
                "Sum of received dividend for the share",
                common_labels
            )

            self.sb_share_info = prometheus_client.Gauge(
                "sb_share_info",
                "Share informations as label",
                common_labels + ['share_currency', 'share_exchange', 'quote_type']
            )
        else:
            raise InvalidConfigFile(self.validator.errors)

    def validate(self):
        return self.validator.validate({"shares": self.configuration['shares'].get()})

    def expose_metrics(self):
        for share in self.configuration['shares'].get():
            label_values = [share['name'], share['symbol']]

            self.sb_random_variable.labels(*label_values).set(random.randint(1, 100))

            self.sb_purchased_quantity.labels(
                *label_values).set(share['purchase']['quantity'])
            self.sb_purchased_price.labels(
                *label_values).set(share['purchase']['cost_price'])
            self.sb_purchased_fee.labels(
                *label_values).set(share['purchase']['fee'])
            self.sb_owned_quantity.labels(
                *label_values).set(share['estate']['quantity'])
            self.sb_received_dividend.labels(
                *label_values).set(share['estate']['received_dividend'])

        # try:
        # ticker = yf.Ticker(share['symbol'])
        # history = ticker.history()
        # last_quote = (history.tail(1)['Close'].iloc[0])
        # self.sb_share_price.labels(*label_values).set(last_quote)
        # info_values = label_values + [ticker.info.get('currency', 'undefined'), ticker.info.get('exchange', 'undefined'), ticker.info.get('quoteType', 'undefined')]
        # self.sb_share_info.labels(*info_values).set(1)
        # except (u_exceptions.NewConnectionError, RuntimeError):
        # app_logger.error(
        #     "Error while retrieving data from Yfinance API", exc_info=True)

    def run(self):
        self.configuration.reload()

        if not self.validate():
            raise InvalidConfigFile(self.validator.errors)

        self.expose_metrics()


if __name__ == "__main__":
    app_logger.info('SuiviBourse is running !')

    # Load config
    config = Configuration('SuiviBourse', __name__)

    # Load schema file
    with open(Path(__file__).parent / "schema.yaml", encoding='UTF-8') as f:
        dataSchema = yaml.safe_load(f)
    shares_validator = Validator(dataSchema)

    try:
        # Start up the server to expose the metrics.
        prometheus_client.start_http_server(
            int(os.getenv('SB_METRICS_PORT', default='8081')))
        # Init SuiviBourseMetrics
        sb_metrics = SuiviBourseMetrics(config, shares_validator)
        # Schedule run the job on startup.
        sb_metrics.run()
        # Start scheduler
        scheduler = BlockingScheduler()
        scheduler.add_job(sb_metrics.run, 'interval', seconds=int(
            os.getenv('SB_SCRAPING_INTERVAL', default='120')))
        scheduler.start()
    except Exception:
        app_logger.critical('An error occurred', exc_info=True)
        sys.exit(1)

 

标签:__,Python,self,labels,share,Prometheus,client,sb
From: https://www.cnblogs.com/lightsong/p/17915108.html

相关文章

  • Python 使用getopt解析命令行参数
    ​ 1、getopt模块此模块可协助脚本解析sys.argv中的命令行参数。它支持与Unixgetopt()函数相同的惯例(包括形式如'-'与'--'的参数的特殊含义)。也能通过可选的第三个参数来使用与GNU软件所支持形式相类似的长选项。1)getopt.getopt(args,shortopts,longopts=[])......
  • Python 调用 FFmpeg 处理合并视频文件
    ​ FFmpeg是一个开源的多媒体框架,它包含了用于处理音频、视频、字幕等多媒体数据的一系列工具、库和软件包。FFmpeg可以执行多种多媒体处理任务,包括转码、剪辑、合并、分离、编解码、流媒体传输等。它被广泛用于多媒体应用程序和流媒体平台中,是一个功能强大且高度可定制的工......
  • Python中强大的动态类型特性,以方法调用为例
    在研究大佬的项目时,从一行行代码溯源,拨茧抽丝的过程中,发现了方法调用的“神奇之处”具体情况如下:1.在类Trainer中名为run等方法中有加载预训练好的模型的load方法2.load()方法依旧是类方法中的一个,在load方法中有具体的load_self()方法3. load_self()定义在另一个py文件mod......
  • python - 批量压缩word图片
    主要分为3个步骤,提取图片,压缩图片,替换图片,需要用到python-docx和pillow1.提取图片importdocxdocName="test.docx"imageIndex=0document=docx.Document(docName)forrelindocument.part.rels.values():if"image"inrel.reltypeandhasattr(rel,"ta......
  • 决策树算法思想及其Python实现
    决策树算法是一种在机器学习和数据挖掘领域广泛应用的强大工具,它模拟人类决策过程,通过对数据集进行逐步的分析和判定,最终生成一颗树状结构,每个节点代表一个决策或一个特征。决策树的核心思想是通过一系列问题将数据集划分成不同的类别或值,从而实现对未知数据的预测和分类。这一算......
  • day17 基于Prometheus的HPA自动伸缩 -Prometheus黑盒监控-自定义资源接入监控系统 (7.
    一、基于Prometheus的HPA自动伸缩1、背景Kubernetes集群规模大、动态变化快,而且容器化应用部署和服务治理机制的普及,传统的基础设施监控方式已经无法满足Kubernetes集群的监控需求。需要使用专门针对Kubernetes集群设计的监控工具来监控集群的状态和服务质量。Prometheus则......
  • apache HttpClient异常-ProtocolException: Target host is not specified
    昨夜,甘肃临夏州积石山县发生6.2级地震,影响到甘肃、青海地区。截至目前,已有100多人遇难。百度了一下当地天气,还挺冷,夜间温度低到-15℃。时间就是生命,祈祷难民尽快得到救援!  分享今天解决的一个生产问题告警。如下HTTP工具类中的httpClientPost方法使用apache的HttpClient(ma......
  • Python的Requests库与网页爬取
    requests库的几种方法 其他几个方法内部实际都调用了requests.request()方法 Response对象的属性 首先要使用r.status_code判断连接是否成功。 Request库的异常  爬取网页的通用代码  需要处理异常,使爬取网页变得更有效、可靠、稳定。  HTTP  无......
  • python中赋值语句教程
    1.赋值语句的特点赋值语句创建对象的引用:赋值语句总是创建对象的引用,而不是复制对象。因此,Python中的变量更像是指针,而不是数据储存区域。变量在首次赋值时会被创建:因此不需要提前声明变量。变量在引用前必须先赋值:如果引用未赋值的变量会报错2.赋值语句的形式(1.普通形......
  • python进行二进制数据处理的方法
    方法一:使用struct模块,特点轻量化,简单易用。缺点就是可读性不是太好,使用小数据临时使用一下,对于大量的数据解析,写起来比较繁琐,显得有点力不从心。importstructdata=b'\x92\xaa\xbb\xcc\x11\x22\x33\x44'a,b,c,d,e=struct.unpack(">BBBBI",data)print("a=0x%xb=0x%xc=......