將獲取的指標封裝成接口提供API請求調用

1.將阿里雲的監控指標推送到企業微信

  • (1)首先須要在項目的根路徑下,建立utils包,用於存放項目的其餘數據接口;html

  • (2)而後在utils包下,建立一個wechat_send.py模塊, 用於給用戶封裝企業微信的接口,提供給外界調用;python

import requests
import json

class Wechat_Info:
    def __init__(self):
        self.partyID = '1'
        self.corpID = 'ww5cfabaf35ce8cd7b'
        self.secret = 'uiwvmNj8f1IVy3QYrZ62WePGFKA_BsIPmHigq3TRydM'
        self.agentID = '1000002'
        self.token = None

    def __get_token(self, corpid, secret):
        Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
        Data = {
            "corpid": corpid,
            "corpsecret": secret
        }
        r = requests.get(url=Url, params=Data)
        token = r.json()['access_token']
        return token

    def send_message(self, message):
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}".format(
            self.__get_token(self.corpID, self.secret))
        data = {
            "toparty": self.partyID,
            "msgtype": "text",
            "agentid": self.agentID,
            "text": {
                "content": message
            },
            "safe": "0"
        }
        result = requests.post(url=url, data=json.dumps(data))
        return result.text
if __name__ == '__main__':
    wechat_info = Wechat_Info()
    result = wechat_info.send_message('微信測試')
    print(result)
  • (3)因爲partyIDcorpIDsecretagentID都是配置信息,須要引入一個讀取配置文件的庫configparser
安裝:
pip install configparser
  • (4)爲了管理全部的配置文件還須要建立一個配置文件目錄cfg,能夠在cfg目錄下建立配置文件,如xkd.conf文件;
[Wechat]
party_id = 1
corp_id = ww5cfabaf35ce8cd7b
secret = uiwvmNj8f1IVy3QYrZ62WePGFKA_BsIPmHigq3TRydM
agent_id = 1000002
  • (5)而後能夠在utils包下,建立一個const_file.py文件,依賴做爲項目中全局常量的引用;
import os
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_DIR = os.path.join(PROJECT_DIR, 'cfg')
# 指定配置文件的路徑
CONFIG_FILE = os.path.join(CONFIG_DIR, 'xkd.conf')
  • (6)接着修改wechat_send.py模塊接口(配置中的信息都是明文的,在項目開發中,最好將重要的配置信息進行加密,能夠使用base64進行加密和解密);
import requests
import json
from configparser import ConfigParser
from utils.const_file import CONFIG_FILE

class Wechat_Info:
    def __init__(self):
        self.wechat_info = self.__get_config_info()

    def __get_config_info(self):
        parser = ConfigParser()
        parser.read(CONFIG_FILE)
        wechat_info = {}
        wechat_info['party_id'] = parser.get('Wechat', 'party_id')
        wechat_info['corp_id'] = parser.get('Wechat', 'corp_id')
        wechat_info['secret'] = parser.get('Wechat', 'secret')
        wechat_info['agent_id'] = parser.get('Wechat', 'agent_id')
        return wechat_info

    def __get_token(self, corpid, secret):
        Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
        Data = {
            "corpid": corpid,
            "corpsecret": secret
        }
        r = requests.get(url=Url, params=Data)
        token = r.json()['access_token']
        return token
    def send_message(self, message):
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}".format(
            self.__get_token(self.wechat_info.get('corp_id'), self.wechat_info.get('secret')))
        data = {
            "toparty": self.wechat_info.get('party_id'),
            "msgtype": "text",
            "agentid": self.wechat_info.get('agent_id'),
            "text": {
                "content": message
            },
            "safe": "0"
        }
        result = requests.post(url=url, data=json.dumps(data))
        return result.text
if __name__ == '__main__':
    wechat_info = Wechat_Info()
    result = wechat_info.send_message('微信測試')
    print(result)
  • (7)在utils包下,建立aliyun_monitor.py文件,封裝阿里雲的雲監控數據的接口;django

  • (8)而後編輯xkd.conf配置文件,添加阿里雲RAM access key 和 access key secretregion idjson

[Wechat]
party_id = 1
corp_id = wwabdfbc8feeee095a
secret = NY2nQE1cavlug_IuyMoRlIZDIOdsDS4KMpo_81XWslo
agent_id = 1000002

[ALIYUN]
access_key = LTAIxdvbuz2MD74Z
access_key_secret = I2b7O1UJmkjfgHVC4i7Atb8gGXwAbU
region_id = cn-shenzhen
  • (9)編輯aliyun_monitor.py文件;
from aliyunsdkcore import client
from aliyunsdkcms.request.v20180308 import QueryMetricListRequest
from datetime import datetime, timedelta
import json
from configparser import ConfigParser
from utils.const_file import CONFIG_FILE

class CloudMonitor:
    def __init__(self):
        self.ram_info = self.__get_ram_info()
        self.clt = client.AcsClient(self.ram_info.get('access_key'), self.ram_info.get('access_key_secret'), self.ram_info.get('region_id'))
        self.request = QueryMetricListRequest.QueryMetricListRequest()
        self.last_average = None

    def __get_ram_info(self):
        parser = ConfigParser()
        parser.read(CONFIG_FILE)
        ram_info = {}
        ram_info['access_key'] = parser.get('ALIYUN', 'access_key')
        ram_info['access_key_secret'] = parser.get('ALIYUN', 'access_key_secret')
        ram_info['region_id'] = parser.get('ALIYUN', 'region_id')
        return ram_info

    def __get_start_timestamp(self):
        start_datetime = datetime.now() - timedelta(minutes=3)
        start_timestamp = int(start_datetime.timestamp() * 1000)
        return start_timestamp

    def get_last_metric(self,instance_id, monitor_key):
        '''
        :param instance_id: ECS是實例ID
        :param monitor_key: 須要監控的指標
        :return:
        '''
        self.request.set_accept_format('json')
        self.request.set_Project('acs_ecs_dashboard')
        self.request.set_Metric('{}'.format(monitor_key))
        start_time = self.__get_start_timestamp()
        self.request.set_StartTime(start_time)
        self.request.set_EndTime(int(datetime.now().timestamp() * 1000))
        self.request.set_Dimensions("{'instanceId': '%s'}" % (instance_id))
        result = self.clt.do_action_with_exception(self.request)
        result = json.loads(result)
        data_str = result.get('Datapoints')
        data_list = json.loads(data_str)
        return data_list[-1]['Average']
if __name__ == '__main__':
    monitor  = CloudMonitor()
    result = monitor.get_last_metric('i-wz98bynewgl7gu3jqqb3', 'CPUUtilization')
    print(result)
  • (10)使用Django定時任務庫,須要用到django-crontab;
pip install django-crontab
  • (11)而後在settings文件中添加django-crontab到INSTALLED_APPS;
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users',
    'courses',
    'teachers',
    'schools',
    'rest_framework',
    'django_crontab',
]
  • (12)在users APP下建立一個cron.py文件,導入import CloudMonitorWechat_Info
from utils.aliyun_monitor import CloudMonitor
from utils.wechat_send import Wechat_Info
def send_aliyun_metric_to_wechat():
    monitor = CloudMonitor()
    wechat_info = Wechat_Info()
    result = monitor.get_last_metric('i-wz98bynewgl7gu3jqqb3', 'CPUUtilization')
    wechat_info.send_message('當前服務器CPU使用率是:{}'.format(result))
  • (13)在settings文件中配置定時任務CRONJOBS;
CRONJOBS = [
    ('* * * * *', 'users.cron.send_aliyun_metric_to_wechat')
]
  • (14)最後添加定時任務:python manage.py crontab add

2.configparser模塊

  • 安裝命令行:pip install configparserwindows

  • ConfigParser是用來讀取配置文件的模塊,配置文件的格式跟windows下的ini配置文件類似,能夠包含一個或多個section,每一個section都有本身的option;api

  • section 用 [sect_name] 表示,每一個option是一個鍵值對,使用分隔符=:隔開;服務器

  • 在 option 中分隔符兩端的空格會被忽略掉;微信

  • 配置文件使用能夠使用#進行註釋;session

3.django-crontab庫

安裝命令:
pip install django-crontab
  • django-crontab使用前須要添加到settings文件中的INSTALLED_APPS中;post

  • 添加定時任務:python manage.py crontab add,注意若是修改了任務,也須要再次運行此命令;

  • 清除定時任務:python manage.py crontab remove

  • 顯示定時任務:python manage.py crontab show

  • 注意django-crontab必須在Linux的crontab開啓的狀況下方可以使用,否則會出現不執行的狀況;

參考:https://www.9xkd.com/user/plan-view.html?id=2761461821

相關文章
相關標籤/搜索