Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2279510
  • 博文数量: 297
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2200
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-31 14:30
个人简介

自己慢慢积累。

文章分类

全部博文(297)

分类: Python/Ruby

2024-11-13 11:59:38

execute_case 为主进程,通过 threading.Thread 创建子进程;
当页面点击停止进程,就调用 stop_thread 方法,获取到进程名称和id 后,通过_async_raise 杀掉进程

点击(此处)折叠或打开

  1. def _async_raise(tid, exctype):
  2.     """raises the exception, performs cleanup if needed"""
  3.     tid = ctypes.c_long(tid)
  4.     if not inspect.isclass(exctype):
  5.         exctype = type(exctype)
  6.     res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
  7.     if res == 0:
  8.         raise ValueError("invalid thread id")
  9.     elif res != 1:
  10.         ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
  11.         raise SystemError("PyThreadState_SetAsyncExc failed")




  12. def stop_thread_fun(thread):
  13.     _async_raise(thread.ident, SystemExit)




  14. def stop_thread(request):
  15.     # 杀掉未执行完成的进程
  16.     current_user = request.session['user_name']
  17.     thread_name = f'Thread-{current_user}'
  18.     log.info(f"执行 stop_thread,获取的线程名字:{thread_name}")
  19.     ts = threading.enumerate()
  20.     for t in ts:
  21.         log.info(f"t.name:{t.name}, t.ident:{t.ident}, t.is_alive():{t.is_alive()}")
  22.         if t.name == thread_name:
  23.             log.info(f'Goodbye {thread_name}!')
  24.             stop_thread_fun(t)
  25.     return redirect('/case_run')




  26. @csrf_exempt
  27. def execute_case(request):
  28.     if not request.session.get('is_login', None):
  29.         # 如果未登录
  30.         return redirect("/login/")
  31.     log.info('+++++++++++ 获取要执行的模块 ++++++++++')
  32.     if request.method == 'POST':
  33.         current_user = request.session['user_name']
  34.         test_url = request.POST['test_http']
  35.         test_mode = request.POST.getlist('test_module')


  36.         request.session['select_case'] = test_mode


  37.         # 将list转为str
  38.         ss = ""
  39.         for j in test_mode:
  40.             ss = ss + j + ','


  41.         # 去掉{BANNED}最佳后一个逗号
  42.         test_mode = ss[:-1]
  43.         # 插入数据库
  44.         cursor = connection.cursor()
  45.         cursor.execute(f"delete from test_config where creator='{current_user}'")
  46.         cursor.execute("insert into test_config(test_url, test_module, creator) values(%s,%s,%s)",
  47.                        [test_url, test_mode, current_user])
  48.     # 调用子进程
  49.     log.info("调用子进程执行!!")
  50.     current_user = request.session['user_name']
  51.     t = threading.Thread(target=fork_execute, args=(request, current_user,))
  52.     t.setName(f'Thread-{current_user}')
  53.     t.setDaemon(True)
  54.     t.start()


  55.     return redirect(f"/case_run/")


阅读(62) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~