execute_case 为主进程,通过 threading.Thread 创建子进程;
当页面点击停止进程,就调用 stop_thread 方法,
获取到进程名称和id 后,通过
_async_raise 杀掉进程
-
def _async_raise(tid, exctype):
-
"""raises the exception, performs cleanup if needed"""
-
tid = ctypes.c_long(tid)
-
if not inspect.isclass(exctype):
-
exctype = type(exctype)
-
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
-
if res == 0:
-
raise ValueError("invalid thread id")
-
elif res != 1:
-
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
-
raise SystemError("PyThreadState_SetAsyncExc failed")
-
-
-
-
-
def stop_thread_fun(thread):
-
_async_raise(thread.ident, SystemExit)
-
-
-
-
-
def stop_thread(request):
-
# 杀掉未执行完成的进程
-
current_user = request.session['user_name']
-
thread_name = f'Thread-{current_user}'
-
log.info(f"执行 stop_thread,获取的线程名字:{thread_name}")
-
ts = threading.enumerate()
-
for t in ts:
-
log.info(f"t.name:{t.name}, t.ident:{t.ident}, t.is_alive():{t.is_alive()}")
-
if t.name == thread_name:
-
log.info(f'Goodbye {thread_name}!')
-
stop_thread_fun(t)
-
return redirect('/case_run')
-
-
-
-
-
@csrf_exempt
-
def execute_case(request):
-
if not request.session.get('is_login', None):
-
# 如果未登录
-
return redirect("/login/")
-
log.info('+++++++++++ 获取要执行的模块 ++++++++++')
-
if request.method == 'POST':
-
current_user = request.session['user_name']
-
test_url = request.POST['test_http']
-
test_mode = request.POST.getlist('test_module')
-
-
-
request.session['select_case'] = test_mode
-
-
-
# 将list转为str
-
ss = ""
-
for j in test_mode:
-
ss = ss + j + ','
-
-
-
# 去掉{BANNED}最佳后一个逗号
-
test_mode = ss[:-1]
-
# 插入数据库
-
cursor = connection.cursor()
-
cursor.execute(f"delete from test_config where creator='{current_user}'")
-
cursor.execute("insert into test_config(test_url, test_module, creator) values(%s,%s,%s)",
-
[test_url, test_mode, current_user])
-
# 调用子进程
-
log.info("调用子进程执行!!")
-
current_user = request.session['user_name']
-
t = threading.Thread(target=fork_execute, args=(request, current_user,))
-
t.setName(f'Thread-{current_user}')
-
t.setDaemon(True)
-
t.start()
-
-
-
return redirect(f"/case_run/")