现在只是在初步试验阶段。
背景:有时候官网突然很慢,开发测试业务人员都不知道,所以想着写一个小工具,每隔五分钟获取一次接口信息所需要的时间,如果超过五秒,连续请求三次,三次都超过五秒,则邮件通知。(由于用了response的elapsed.total_seconds()不确定是否真的有效,这里主要是展示框架,其中的小功能有所欠缺的,后续再完善)
一、获取接口返回数据所花费的时间以及获取接口时的时间点写入csv文件(还未接入发送邮件功能)
#timing.py
import requests, time, csv
def run():
r = requests.get("http://www.XXXX.com")
inttime = r.elapsed.total_seconds()
# inttime = 10
usetime = str(inttime)
if inttime < 5:
print("enter less five mins")
writetime(usetime)
else:
print("enter more five mins")
writetime(usetime)
for i in range(3):
r = requests.get("http://www.XXX.com")
inttime = r.elapsed.total_seconds()
usetime = str(inttime)
writetime(usetime)
def writetime(usetime):
with open("./time.csv", "a+") as b:
csv_writer = csv.writer(b)
now = str(time.ctime())
print(now)
csv_writer.writerow([now, usetime])
run()
csv的第一行需要自己手动写入,不然django在获取csv的时候,dict会显示不正确
示例:
Time,XXX
Tue Jan 5 10:55:44 2021,0.107115
Tue Jan 5 10:55:44 2021,0.107115
二、django写一个接口,将csv中的数据 返回给前端。
原本我想直接写一个html,读取服务器上的csv,展示到前台就好了,结果问了前端,也和前端一起实战了一下,无法实现成功,所以只能用django写个接口,然后前台用vue展示。
django的搭建及配置我就不说了,自行百度,我直接记录下要点。(项目名叫:time_project)
先来看下项目的层级目录:
.
└── Django
├── db.sqlite3
├── Django
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── settings.py
│ ├── settings.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── wsgi.py
│ └── wsgi.pyc
├── manage.py
└── time_project
├── admin.py
├── admin.pyc
├── apps.py
├── __init__.py
├── __init__.pyc
├── migrations
│ ├── __init__.py
│ └── __init__.pyc
├── models.py
├── models.pyc
├── tests.py
├── views.py
└── views.pyc
1.在views.py中写接口细节
路径:/Django/time_project/views.py
#views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
import json, csv
from django.http import HttpResponse
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
def getCsvValue():
dictList = []
with open("/root/coding/function/time.csv") as file:
datareader = csv.reader(file)
csvList = list(datareader)
keyList = csvList[0]
for value in range(1, len(csvList)):
csvDict = {};
for item in range(0, len(keyList)):
csvDict[keyList[item]] = csvList[value][item];
print(csvDict)
dictList.append(csvDict)
return dictList
@csrf_exempt
def time(request):
dic = {}
if request.method == 'GET':
a = getCsvValue()
dic["message"] = a
return HttpResponse(json.dumps(dic))
else:
dic['message'] = '方法错误'
return HttpResponse(json.dumps(dic, ensure_ascii=False))
# Create your views here.
getCsvValue() 是获取csv中的数据,并且返回list
样例:[{'Time': 'Tue Jan 5 10:55:44 2021', 'XXX': '0.107115'},{'Time': 'Tue Jan 5 10:55:44 2021', 'XXX': '0.107115'}]
2.配置urls,导入刚刚写的接口
路径:/Django/Django/urls.py
#urls.py
"""Django URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from time_project import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^time$',views.time, name="time"),
]
此时访问localhost:port/time 就能返回数据了
3.跨域
我这边django用了8888接口,vue使用了8081接口,所以在vue访问8081的时候,有个跨域的问题,需要再django这边配置
3.1 安装django-cors-headers
pip install django-cors-headers
3.2 配置settings.py文件(主要是几个点,添加一下)
路径:/Django/Django/settings.py
INSTALLED_APPS = [
...
'corsheaders',
...
]
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware', # 注意顺序
...
)
#跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = ()
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
4.非本地也能访问接口(使用ip也能访问)
python manage.py runserver 0.0.0.0:8888(使用0.0.0.0,即可ip访问,不然只能localhost访问)
三、vue部分
先看下层级目录:
.
└── vue_time
├── build
│ ├── build.js
│ ├── check-versions.js
│ ├── logo.png
│ ├── utils.js
│ ├── vue-loader.conf.js
│ ├── webpack.base.conf.js
│ ├── webpack.dev.conf.js
│ └── webpack.prod.conf.js
├── config
│ ├── dev.env.js
│ ├── index.js
│ ├── prod.env.js
│ └── test.env.js
├── index.html
├── package.json
├── README.md
├── src
│ ├── api
│ │ └── api.js
│ ├── App.vue
│ ├── assets
│ │ └── logo.png
│ ├── components
│ │ ├── HelloWorld.vue
│ │ ├── time.vue
│ │ └── time.vue_bak
│ ├── main.js
│ └── router
│ └── index.js
├── static
├── test
│ ├── e2e
│ │ ├── custom-assertions
│ │ │ └── elementCount.js
│ │ ├── nightwatch.conf.js
│ │ ├── runner.js
│ │ └── specs
│ │ └── test.js
│ └── unit
│ ├── jest.conf.js
│ ├── setup.js
│ └── specs
│ └── HelloWorld.spec.js
└── vue.config.js
1.time.vue
路径:vue_time/src/components/time.vue
主要是知识点:
1.1.使用element-ui来绘制表格
1.2.script中时基本显示逻辑
1.3.methods中相互引用使用:this.$options.methods.
//time.vue
<template>
<div>
<el-table
:data="tableData"
style="width: 100%">
<el-table-column
prop="Time"
label="时间点"
width="500">
</el-table-column>
<el-table-column
prop="zhaoonline"
label="首页花费时间"
width="500">
</el-table-column>
<el-table-column
prop="address"
label="备注">
</el-table-column>
</el-table>
</div>
</template>
<script>
import { timeConfig } from '../api/api';
export default {
data() {
return {
tableData: []
}
},
methods: {
gettime() {
let self = this;
timeConfig().then((res) => {
this.tableData =this.$options.methods.reserse1(res.message);
console.log(res);
})
},
reserse1(array){
var newArr = [];
for(var i=array.length-1;i>=0;i--){
newArr[newArr.length] = array[i];
}
return newArr;
},
},
mounted() {
this.gettime();
},
}
</script>
2.element-ui需要在main.js中引入,不然会报 找不到还是没定义el-table的错误
//main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App'
import router from './router'
Vue.config.productionTip = false
Vue.use(ElementUI);
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
3.index.js
路径:vue_time/src/router/index.js 建立time的路由
//index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import time from '@/components/time'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/time',
name: 'time',
component: time
}
]
})
4.api.js
路径:vue_time/src/api
时间接口,其中timeConfig在第一步中用到了
import axios from 'axios';
// 时间接口对接
export const timeConfig = params => { return axios.get(`http://192.168.0.189:8888/time`, params).then(res => res.data); };
四、定时任务,每五分钟抓一次接口返回时间
用了shell来执行,本来要用crontab执行的,可是 数据没有写入csv,具体原因后续再查一下,暂时只能写个shell了
#!/bin/bash
while true
do
python /root/coding/function/timing.py
sleep 5m
done
echo "done"
执行命令:nohup ./crontab.sh &
项目的启动:
目录下有三个文件夹:django_pro function vue_pro
分别是:django代码,python执行接口及写入csv代码,vue代码
启动django命令:
到目录:/root/coding/django_pro/Django
执行:python manage.py runserver 0.0.0.0:8888
启动vue命令:
到目录:/root/coding/vue_pro/vue_time
执行:npm run dev
有个shell定时任务,每五分钟运行一次:
脚本位置:/root/coding/function
执行:nohup ./crontab.sh &
说明:nohup是后台运行,&是即便关闭窗口也不会关闭shell运行程序