大数据 爬虫Python AI Sql小猿圈-IT自学人的小圈子

小猿圈利用Python和Prometheus跟踪天气

2019-06-25  本文已影响2人  f673630174f6

现在人工智能越来越实用,甚至深入到千家万户,随之而来的就是python技术的火爆,今天小猿圈python讲师为你讲解一下利用Python和Prometheus跟踪天气的详解,希望对于刚刚自学python的你有一定的帮助。

开源监控系统Prometheus集成了跟踪多种类型的时间序列数据,但如果没有集成你想要的数据,那么很容易构建一个。一个经常使用的例子使用云端提供商的自定义集成,它使用提供商的API抓取特定的指标。但是,在这个例子中,我们将与最大云端提供商集成:地球。

幸运的是,美国政府已经测量了天气并为集成提供了一个简单的API。获取红帽总部下一个小时的天气预报很简单。

import requests

HOURLY_RED_HAT = "<https://api.weather.gov/gridpoints/RAH/73,57/forecast/hourly>"

def get_temperature():

    result = requests.get(HOURLY_RED_HAT)

    return result.json()["properties"]["periods"][0]["temperature"]

现在我们已经完成了与地球的集成,现在是确保Prometheus能够理解我们想要内容的时候了。我们可以使用PrometheusPython库中的gauge创建一个注册项:红帽总部的温度。

from prometheus_client import CollectorRegistry, Gauge

def prometheus_temperature(num):

    registry = CollectorRegistry()

    g = Gauge("red_hat_temp", "Temperature at Red Hat HQ", registry=registry)

    g.set(num)

    return registry

最后,我们需要以某种方式将它连接到Prometheus。这有点依赖Prometheus的网络拓扑:是Prometheus与我们的服务通信更容易,还是反向更容易。

第一种是通常建议的情况,如果可能的话,我们需要构建一个公开注册入口的Web服务器,并配置Prometheus收刮(scrape)它。

我们可以使用Pyramid构建一个简单的Web服务器。

from pyramid.config import Configurator

from pyramid.response import Response

from prometheus_client import generate_latest, CONTENT_TYPE_LATEST

def metrics_web(request):

    registry = prometheus_temperature(get_temperature())

    return Response(generate_latest(registry),

                              content_type=CONTENT_TYPE_LATEST)

config = Configurator()

config.add_route('metrics', '/metrics')

config.add_view(metrics_web, route_name='metrics')

app = config.make_wsgi_app()

这可以使用任何Web网关接口(WSGI)服务器运行。例如,假设我们将代码放在earth.py中,我们可以使用python-mtwistedweb--wsgiearth.app来运行它。

或者,如果我们的代码连接到Prometheus更容易,我们可以定期将其推送到Prometheus的推送网关。

import time

from prometheus_client import push_to_gateway

def push_temperature(url):

    while True:

        registry = prometheus_temperature(get_temperature())

        push_to_gateway(url, "temperature collector", registry)

        time.sleep(60*60)

以上就是小猿圈python讲师给大家分享的利用Python和Prometheus跟踪天气的介绍,希望对小伙伴们有所帮助Python交流群:874680195,想要了解更多内容的小伙伴可以到小猿圈直接观看,想要学好Python开发技术的小伙伴快快行动吧。

上一篇 下一篇

猜你喜欢

热点阅读