阿里云CDN刷新项目

 

 

aliyun_cdn刷新项目

背景:公司正处于发展期,IOS 安卓 还有前端等项目频繁发布 时间不固定 运维人员人手不够

所有每次发布都要刷新CDN相关目录 况且如果让开发人员等操作刷新CDN还要登录aliyun相关帐号

这样导致帐号不安全和流程不合适

所以诞生自主研发CDN刷新功能

系统环境:

centos7.4

python 3.7

flask 框架

aliyun核心sdk和cdn sdk

bootstrap框架

系统安全上面

只限openv*n登录访问内网才可以操作

项目截图:

阿里云CDN刷新项目

/templates/index.html

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <title>cdn</title>
   <!-- 新 Bootstrap 核心 CSS 文件 -->
   <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
   <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
   <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
   <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
   <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="col-xs-6">
        <div class="box" >
            <div class="box-header">
                <h3 class="box-title"> 刷新上限2000-----目录上限100</h3>
                 <form class="form-inline" role="form">
                     <div class="form-group">
                         {% if urlcount < 500 %}
                            <button type="button" class="btn btn-danger">刷新剩余:{{ urlcount }}</button>
                         {% else %}
                            <button type="button" class="btn btn-success">刷新剩余:{{ urlcount }}</button>
                         {% endif %}
                     </div>
                     <div class="form-group">
                         {% if urlcount < 50 %}
                            <button type="button" class="btn btn-danger">目录剩余:{{ dircount }}</button>
                         {% else %}
                            <button type="button" class="btn btn-success">目录剩余:{{ dircount }}</button>
                         {% endif %}
                     </div>
                 </form>
            </div>
        </div>
        <div class="box" >
            <div class="box-header">
                <h3 class="box-title">CDN刷新操作</h3>
            </div>
            <form class="form-inline" role="form" method="get" action="shuaxin">
               <div class="form-group">
                  <label>输入URL</label>
                  <input type="text" class="form-control" id="url" name="url" placeholder="请输入名称">
               </div>
                <div class="form-group">
                     <select class="form-control select2" id="type" name="type" style="width: 100%; ">

                          <option>URL刷新</option>
                          <option>目录刷新</option>

                    </select>
                </div>
                <div class="form-group">
                    <button type="submit" value="Submit" class="btn btn-default">提交</button>
                </div>
            </form>
        </div>
        <div class="box">
            <div class="box-header">
                <h4 class="box-title">操作记录</h4>
            </div>
            <div class="box-body">
                <table id="example2" class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <th>执行时间</th>
                            <th>URL</th>
                            <th>操作</th>
                            <th>结果</th>
                            <th>类型</th>
                            <th>进度</th>
                            <th>TaskID</th>
                        </tr>
                    </thead>
                    <tbody>
                    {% for k in info %}
                        <tr>
                            <td>{{ k.CreationTime }}</td>
                            <td>{{ k.ObjectPath }}</td>
                            {% if k.ObjectType == "file" %}
                                <td><div><a class="btn btn-primary btn-xs" href="/shuaxin?url={{ k.ObjectPath }}&type=file" target="_blank">再次操作</a></div></td>
                            {% else %}
                                <td><div><a class="btn btn-primary btn-xs" href="/shuaxin?url={{ k.ObjectPath }}&type=directory" target="_blank">再次操作</a></div></td>
                            {% endif %}

                            {% if k.Status == "Complete" %}
                                <td>完成</td>
                            {% else %}
                                <td>异常</td>
                            {% endif %}
                            {% if k.ObjectType == "file" %}
                                <td>URL刷新</td>
                            {% else %}
                                <td>目录刷新</td>
                            {% endif %}
                            <td>{{ k.Process }}</td>
                            <td>{{ k.TaskId }}</td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</body>
</html>

 

/templates/shuaxin.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>跳转页面</title>
 <script>
        var count = 2;
        var t;
        function writeTip(){
            document.getElementById("d").innerHTML = "<a href='/'> {{ info }}     页面将在"+(count--)+"秒内跳转到首页</a>";
            if(count==0){
                window.clearInterval(t);
                window.location = "/";
            }
        }
        t = window.setInterval("writeTip()",1000);
    </script>
</head>
<body>
    <div id="d">
        <a href='/'>{{ info }}     页面将在3秒内跳转到首页</a>
    </div>
</body>
</html>

 

app.py

from flask import Flask,render_template
from flask import request
from aliyunsdkcore import client
import json
import datetime
from dateutil.parser import parse
from aliyunsdkcdn.request.v20141111 import DescribeRefreshTasksRequest  # 引入获取CDN刷新操作日志类
from aliyunsdkcdn.request.v20141111 import RefreshObjectCachesRequest   # 引入刷新CDN的类
from aliyunsdkcdn.request.v20141111 import DescribeRefreshQuotaRequest  # 引入获取剩余刷新次数的类
Client=client.AcsClient('xxxxxxxxx','xxxxxxxxxxxxxxxxxxxxxxx','cn-hangzhou')
app = Flask(__name__)

def get_aliyun_cdn_log():
    request = DescribeRefreshTasksRequest.DescribeRefreshTasksRequest()
    request.set_accept_format('json')
    request.set_PageNumber(1)  # 取得第几页 取值范围为:1~100000
    request.set_PageSize(50)  # 分页大小,默认20,最大50 取值:1~50之前的任意整数
    data = json.loads(Client.do_action(request)).get("Tasks").get("CDNTask")
    # 处理时间:阿里云返回的时间格式是UTC,现处理成北京时间,把字符格式转换成时间格式,并+8小时
    for i in data:
        i['CreationTime'] = (parse(i['CreationTime']) + datetime.timedelta(hours=8)).strftime('%Y-%m-%d %H:%M:%S')
    return json.dumps(data)
def shuaxin_cdn(url_path,s_type):
    request = RefreshObjectCachesRequest.RefreshObjectCachesRequest()
    request.set_ObjectPath(url_path)  # 刷新地址
    request.set_ObjectType(s_type)  # 地址类型
    request.set_accept_format('json')
    Client.do_action(request)  # 刷新
    return "刷新完成,稍等会即生效"
def shengyu_count():
    request = DescribeRefreshQuotaRequest.DescribeRefreshQuotaRequest()
    request.set_accept_format('json')
    result = json.loads(Client.do_action(request))
    result['UrlPer'] = format(float(result.get('UrlRemain')) / float(result.get('UrlQuota')), '.2%')  # 统计URL当日可刷新量百分比
    result['DirPer'] = format(float(result.get('DirRemain')) / float(result.get('DirQuota')), '.2%')  # 统计目录当日可刷新量百分比
    return result
@app.route('/')
def hello_world():
    count=shengyu_count()
    urlcount=count['UrlRemain']
    dircount=count['DirRemain']
    # return 'Hello World!'
    return render_template('index.html',info=json.loads(get_aliyun_cdn_log()),urlcount=int(urlcount),dircount=int(dircount))
@app.route('/test')
def test():
    # return 'Hello World!'
    return render_template('shuaxin.html')
@app.route('/shuaxin', methods=['post','get'])
def shuaxin():
    url = request.args.get('url')
    type = request.args.get('type')
    s_type=''
    if type=="URL刷新":
        s_type='file'
    elif type=="目录刷新":
        s_type='directory'

    info=shuaxin_cdn(url, type)
    # info=url+'   '+s_type
    return render_template('shuaxin.html', info=info)

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