python 通过openapi 获取nacos服务列表生成Prometheus的exporter配置文件
2022/6/7 1:21:56
本文主要是介绍python 通过openapi 获取nacos服务列表生成Prometheus的exporter配置文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
# pip install uvicorn # pip install fastapi # uvicorn main:app --reload # pip install ruamel.yaml from fastapi import FastAPI from fastapi.responses import PlainTextResponse import uvicorn , json, requests, os from ruamel import yaml curpath = os.path.dirname(os.path.realpath(__file__)) yamlpath = os.path.join(curpath, "test.yml") app = FastAPI() nacosurl = 'http://192.168.1.2:8848/nacos' groupName = 'DEFAULT_GROUP' namespaceId = 'test' @app.get('/metrics', response_class=PlainTextResponse) async def get_metrics(): servicesQryData = {'pageNo':'1', 'pageSize':'1024', 'namespaceId': namespaceId, 'groupName': groupName} sqr = requests.get(url=nacosurl + "/v1/ns/service/list", params=servicesQryData) if sqr.status_code != 200: print('query service list error, ' + sqr.text) return serviceRspJson = json.loads(sqr.text) strbuf = [] srvnode = {} for sn in serviceRspJson.get('doms'): itemQryData = {'serviceName':sn, 'namespaceId': namespaceId, 'groupName': groupName} snr = requests.get(url=nacosurl + '/v1/ns/instance/list', params=itemQryData) if snr.status_code != 200: print('query service instance error, ' + snr.text) continue service_nodes = json.loads(snr.text)['hosts'] for srvn in service_nodes: srvnode["targets"] = [srvn['ip'] + ':' + str(srvn['port'])] srvnode["labels"] = {"servicename": sn + '_' +srvn['ip']} strbuf.append(srvnode) # print(strbuf) # 消除数据格式 否则出现 - *id001 newdata = json.loads(json.dumps(strbuf)) #stt = [{'targets': ['192.168.1.201:20023'], 'labels': {'servicename': 'svgauthentication_192.168.1.201'}}] with open(yamlpath, 'w', encoding='utf-8') as fp: yaml.dump(newdata, fp,Dumper=yaml.RoundTripDumper) @app.on_event('startup') def init_scheduler(): pass if __name__ == "__main__": uvicorn.run(app='get_nacos_service:app', host="127.0.0.1", port=8000,reload=True, debug=True)
这篇关于python 通过openapi 获取nacos服务列表生成Prometheus的exporter配置文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-03用FastAPI掌握Python异步IO:轻松实现高并发网络请求处理
- 2025-01-02封装学习:Python面向对象编程基础教程
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型