如何使用prometheus获得python flaskapi的唯一响应时间

2024-04-23 06:30:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我对普罗米修斯来说都是新手。所以我所做的是,我构建了一个随机API,它使用flask调用另一个API。从API中,我只需要获取响应时间,即函数处理请求所需的时间。我尝试了python Prometheus客户端包,并使用摘要和计数器度量进行了刮取,其中摘要度量与总请求的平均响应时间类似,我需要的只是从函数中刮取的响应时间。下面是我的python应用程序

from flask import Flask, Response
from helpers.middleware import setup_metrics
import prometheus_client
import random
import requests

CONTENT_TYPE_LATEST = str('text/plain; version=0.0.4; charset=utf-8')

app = Flask(__name__)
setup_metrics(app)

@app.route('/test2')
def randomnumber():
    res = requests.get("http://httpbin.org/ip")
    httpbin_response_time = res.elapsed.total_seconds()
    return(res.json())


@app.route('/metrics/')
def metrics():
    return Response(prometheus_client.generate_latest(), mimetype=CONTENT_TYPE_LATEST)   
    ##return generate_latest()



if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)



Middleware.py


from flask import request
import time
import sys
from prometheus_client import Counter, Histogram, Summary

REQUEST_COUNT = Counter(
    'httpbin_request_count', 'HTTPBIN Request Count', ['app_name', 'endpoint']
)
HTTPBIN_RESPOND_TIME = Summary('request_processing_seconds', 'Time spent processing request', ['appname','endpoint']
)


def start_timer():
    request.start_time = time.time()


def stop_timer(response):

    resp_time = time.time() - request.start_time
    HTTPBIN_RESPOND_TIME.labels('flaskapi_server', request.path).observe(resp_time)
    return response

def record_request_data(response):
    REQUEST_COUNT.labels('flaskapi_server', request.path).inc()
    return response

def setup_metrics(app):
    app.before_request(start_timer)
    # The order here matters since we want stop_timer
    # to be executed first
    app.after_request(record_request_data)
    app.after_request(stop_timer)
    ```


this is my code. and I want to get only the response time(i.e., without the average time pr falling on histogram buckets) of /test2/ to be scraped by prometheus.



Tags: fromimportapiappflaskreturntimeresponse