http://1.12.224.200/
账号:test
密码:test
pip命令自行查询相关内容即可
任务模型:
# 任务
class Task(models.Model):
task_name = models.CharField("任务名称", max_length=255, null=False)
task_case = models.CharField("接口任务列表", max_length=255, default=[], null=False)
task_status = models.IntegerField("任务状态", null=False, default=2) # 1:开启, 2:关闭
ding_talk = models.CharField("钉钉推送", null=True, max_length=255) # 钉钉推送地址
task_type = models.IntegerField("定时任务类型", null=False, default=1) # 1.某个时刻 2.多久运行一次 3.每周几运行
task_time = models.CharField("任务时间", null=True, max_length=255) # type=1,时刻
task_hour = models.CharField("任务时间", null=True, max_length=255) # type=2, 小时
task_week_days = models.CharField("周几执行", null=True, max_length=255) # type=3, 周几
task_week_times = models.CharField("周几几点执行", null=True, max_length=255) # type=3, 几点
task_description = models.CharField("任务描述", null=True, max_length=255)
user = models.ForeignKey(Userinfo, on_delete=models.CASCADE)
create_time = models.DateTimeField("创建时间", auto_now_add=True)
update_time = models.DateTimeField("更新时间", auto_now_add=True)
def __str__(self):
return self.task_name
# 任务结果
class Task_result(models.Model):
case = models.ForeignKey(Testcase, on_delete=models.CASCADE)
task_status = models.IntegerField("任务是否成功", null=False)
task_result = models.TextField("任务结果", null=True)
task_runtime = models.DateTimeField("任务执行时间", auto_now_add=True)
task_res_time = models.TextField("接口响应时间", null=True)
task_assert = models.CharField("断言结果", max_length=255, null=True)
task_extract = models.CharField("参数提取", max_length=255, null=True)
task = models.ForeignKey(Task, on_delete=models.CASCADE)
def __str__(self):
return self.task.task_name
获取任务列表:
class GetTask(View):
def post(self, request, *args, **kwargs):
data = json.loads(request.body)
if data["task_name"] == "":
tasks = Task.objects.all().order_by("-create_time")
size_page = data["size_page"]
current_pages = data["current_page"]
case_total = len(tasks)
task_list = []
try:
for task in tasks:
task_dict = {
"task_id": task.id,
"task_name": task.task_name,
"task_cases": task.task_case,
"status": task.task_status,
"task_type": task.task_type,
"username": task.user.username,
"task_description": task.task_description,
"update_time": datetime.strftime(task.update_time, "%Y-%m-%d %H:%M:%S"),
"create_time": datetime.strftime(task.create_time, "%Y-%m-%d %H:%M:%S")
}
task_list.append(task_dict)
p = Paginator(task_list, size_page)
page1 = p.page(current_pages)
current_page = page1.object_list
return JsonResponse({
"code": 200,
"message": "获取任务列表成功",
"content": current_page,
"case_total": case_total,
"size_page": size_page,
"current_page": current_pages
})
except Exception as e:
return JsonResponse({
"code": 100,
"message": "获取任务列表失败",
"Exception": str(e)
})
else:
task_name = data["task_name"]
tasks = Task.objects.filter(task_name__contains=task_name).order_by("-create_time")
size_page = data["size_page"]
current_pages = data["current_page"]
case_total = len(tasks)
task_list = []
try:
for task in tasks:
task_dict = {
"task_id": task.id,
"task_name": task.task_name,
"task_cases": task.task_case,
"status": task.task_status,
"task_type": task.task_type,
"username": task.user.username,
"task_description": task.task_description,
"update_time": datetime.strftime(task.update_time, "%Y-%m-%d %H:%M:%S"),
"create_time": datetime.strftime(task.create_time, "%Y-%m-%d %H:%M:%S")
}
task_list.append(task_dict)
p = Paginator(task_list, size_page)
page1 = p.page(current_pages)
current_page = page1.object_list
return JsonResponse({
"code": 200,
"message": "获取任务列表成功",
"content": current_page,
"case_total": case_total,
"size_page": size_page,
"current_page": current_pages
})
except Exception as e:
return JsonResponse({
"code": 100,
"message": "获取任务列表失败",
"Exception": str(e)
})
获取单个任务:
class Single_task(View):
def post(self, request, *args, **kwargs):
data = json.loads(request.body)
task_id = data["task_id"]
tasks = Task.objects.filter(id=task_id)
task_list = []
for task in tasks:
task_dict = {
"task_name": task.task_name,
"task_time": task.task_time,
"task_hour": task.task_hour,
"task_week_days": task.task_week_days,
"task_week_times": task.task_week_times,
"task_cases": eval(task.task_case),
"task_status": task.task_status,
"ding_talk": task.ding_talk,
"task_type": str(task.task_type),
"task_description": task.task_description,
}
task_list.append(task_dict)
return JsonResponse({
"code": 200,
"message": "获取任务成功",
"content": task_list
})
删除任务:
class Delete_task(View):
def post(self, request, *args, **kwargs):
data = json.loads(request.body)
task_id = data["task_id"]
if task_id == "":
return JsonResponse({
"code": 100,
"message": "必要参数不可为空"
})
elif not Task.objects.filter(id=task_id):
return JsonResponse({
"code": 100,
"message": "删除失败,没有此任务"
})
else:
try:
task = Task.objects.filter(id=task_id)
task.delete()
if scheduler.get_job(job_id=str(task_id)):
# 如果存在相同的ID任务,同时删掉
scheduler.remove_job(job_id=str(task_id))
else:
pass
return JsonResponse({
"code": 200,
"message": "删除任务成功"
})
except Exception as e:
return JsonResponse({
"code": 100,
"message": "删除任务失败",
"Exception": str(e)
})
新增&编辑定时任务:
import hashlib
import json
import logging
import urllib
from datetime import datetime
import re
from urllib.parse import urlencode
import requests
from apscheduler.schedulers.background import BackgroundScheduler
from django.http import JsonResponse
from django_apscheduler.jobstores import DjangoJobStore, register_events
from lapi_app.models.environment_model.environment import Environment
from lapi_app.models.task_case.task import Task, Task_result
from lapi_app.models.testcase_model.testcase import Variable_local, Asserts, Testcase
from lapi_app.models.testcase_model.testcase_tree import Menu
logger = logging.getLogger('django')
scheduler = BackgroundScheduler()
scheduler.add_jobstore(DjangoJobStore(), 'default')
bodys = {
}
# 钉钉推送
HEADERS = {
"Content-Type": "application/json;charset=utf-8"}
def add_task(request):
path = request.get_full_path()
data = json.loads(request.body)
logger.info("path = " + path)
bodys.update(data)
tasks = data["task_cases"]
# 新增任务
if path == "/api/task/add_task":
if data["task_name"] == '':
return JsonResponse({
"code": 100,
"message": "任务名称不可以为空"
})
elif data["task_type"] == 1:
if data["task_time"] is None:
return JsonResponse({
"code": 100,
"message": "任务周期不可以为空"
})
elif data["task_type"] == 2:
if data["task_hour"] == "":
return JsonResponse({
"code": 100,
"message": "任务周期不可以为空"
})
elif data["task_type"] == 3:
if data["task_week_days"] == "" or data["task_week_times"] == "":
return JsonResponse({
"code": 100,
"message": "任务周期不可以为空"
})
elif Task.objects.filter(task_name=data["task_name"]).exists():
return JsonResponse({
"code": 100,
"message": "任务名称已存在"
})
for case in tasks:
if "menu_id" in case.keys() or "step" in case.keys():
if case["menu_id"] is None or case["step"] == '':
return JsonResponse({
"code": 100,
"message": "接口或执行顺序不可以为空"
})
elif "menu_id" not in case.keys() or "step" not in case.keys():
return JsonResponse({
"code": 100,
"message": "接口或执行顺序不可以为空"
})
for i in range(len(tasks)):
for j in range(len(tasks) - i - 1):
if tasks[j]["menu_id"] == tasks[j + 1]["menu_id"]:
return JsonResponse({
"code": 100,
"message": "不能出现同一个接口"
})
if tasks[j]["step"] == tasks[j + 1]["step"]:
return JsonResponse({
"code": 100,
"message": "不能出现同一个执行顺序"
})
try:
task = Task.objects.create(task_name=data["task_name"], task_case=data["task_cases"],
task_type=data["task_type"], ding_talk=data["ding_talk"],
task_time=data["task_time"],
user_id=data["user_id"],
task_hour=data["task_hour"],
task_description=data["task_description"],
task_week_times=data["task_week_times"],
task_week_days=data["task_week_days"],
task_status=data["task_status"])
if data["task_status"] == 1:
if data["task_type"] == 1:
# 某个时刻执行
bodys.update({
"task_id": task.id})
scheduler.add_job(run_task, 'date', id=str(task.id),
run_date=data["task_time"])
register_events(scheduler)
scheduler.start()
elif data["task_type"] == 2:
# 间隔时间性执行
bodys.update({
"task_id": task.id})
scheduler.add_job(run_task, 'interval', id=str(task.id), hour=data["task_hour"])
register_events(scheduler)
scheduler.start()
elif data["task_type"] == 3:
# 每周几点执行
start_time = data["task_week_times"].split(':')
h = int(start_time[0])
m = int(start_time[1])
bodys.update({
"task_id": task.id})
scheduler.add_job(run_task, 'cron', id=str(task.id),
day_of_week=data["task_week_days"], hour=h, minute=m)
register_events(scheduler)
scheduler.start()
return JsonResponse({
"code": 200,
"message": "任务创建成功,任务启动",
"data": data
})
else:
return JsonResponse({
"code": 200,
"message": "任务创建成功,任务未启动",
"data": data
})
except Exception as e:
return JsonResponse({
"code": 100,
"message": str(e),
})
# 编辑任务
elif path == "/api/task/edit_task":
if data["task_name"] == '':
return JsonResponse({
"code": 100,
"message": "任务名称不可以为空"
})
elif data["task_type"] == 1:
if data["task_time"] is None:
return JsonResponse({
"code": 100,
"message": "任务周期不可以为空"
})
elif data["task_type"] == 2:
if data["task_hour"] == "":
return JsonResponse({
"code": 100,
"message": "任务周期不可以为空"
})
elif data["task_type"] == 3:
if data["task_week_days"] == "" or data["task_week_times"] == "":
return JsonResponse({
"code": 100,
"message": "任务周期不可以为空"
})
task_names = Task.objects.exclude(id=data["task_id"])
for t in task_names:
if t.task_name == data["task_name"]:
return JsonResponse({
"code": 100,
"message": "任务名称已存在"
})
for case in tasks:
if "menu_id" in case.keys() or "step" in case.keys():
if case["menu_id"] is