api_calculate.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. from django.contrib import auth
  2. from rest_framework.views import APIView
  3. from rest_framework.response import Response
  4. from rest_framework import status
  5. from rest_framework.authtoken.models import Token
  6. from rest_framework.authentication import BasicAuthentication, TokenAuthentication
  7. from .serializers import UserRegisterSerializer
  8. from django.middleware.csrf import get_token
  9. from django.contrib.auth import login
  10. from api.utils import *
  11. from api.models import File, Mission
  12. import requests
  13. import json
  14. class CalculateAPI(APIView):
  15. def post(self, request):
  16. user = request.user
  17. try:
  18. mission = Mission.objects.get(id=request.data.get('mission'))
  19. except Mission.DoesNotExist:
  20. return failed(message="处理任务控制失败,未找到处理任务")
  21. except Exception as error:
  22. print("处理任务控制失败", error)
  23. return failed(message="处理任务控制失败,未找到处理任务")
  24. command = request.data.get('command')
  25. try:
  26. assert command in ['start', 'pause', 'stop']
  27. except Exception as error:
  28. print("处理任务控制代码错误")
  29. return failed(message="处理任务控制失败,控制代码错误")
  30. if command == 'start':
  31. # 如任务已经启动,则不操作
  32. if not mission.state in ['init', 'pause']:
  33. return success(message="任务正在进行中")
  34. if mission.state in ['done']:
  35. return success(message="任务已完成")
  36. else:
  37. # 非启动任务需要检查任务是否已经开始
  38. if not mission.state == 'calculating':
  39. return failed(message="任务没有在运行,无法暂停或停止")
  40. # 向调度程序提交计算任务
  41. # mission = request.json['mission']
  42. # plans = request.json['plans']
  43. calculateData = {
  44. 'mission': {
  45. 'id': mission.id,
  46. },
  47. 'plans': []
  48. }
  49. rootPlan = mission.own_plans.get(parent=None)
  50. calculateData['plans'].append({
  51. 'id': rootPlan.id,
  52. 'nodes': mission.nodeFile.toJson(),
  53. 'edges': mission.edgeFile.toJson(),
  54. 'children': list(mission.own_plans.filter(parent=rootPlan).values_list('id', flat=True)),
  55. })
  56. rootPlans = [ child for child in mission.own_plans.filter(parent=rootPlan)]
  57. while rootPlans:
  58. tempPlans = rootPlans.copy()
  59. rootPlans = []
  60. for p in tempPlans:
  61. children = [ child for child in mission.own_plans.filter(parent=p)]
  62. # 判断是否父节点存在计算结果,有则作为子节点输入
  63. if hasattr(p.parent, 'own_result'):
  64. calculateData['plans'].append({
  65. 'id': p.id,
  66. 'algorithm': p.algorithm.name,
  67. 'nodes': p.parent.own_result.nodeFile.toJson(),
  68. 'edges': p.parent.own_result.edgeFile.toJson(),
  69. 'children': [child.id for child in children],
  70. })
  71. else:
  72. calculateData['plans'].append({
  73. 'id': p.id,
  74. 'algorithm': p.algorithm.name,
  75. 'nodes': None,
  76. 'edges': None,
  77. 'children': [child.id for child in children],
  78. })
  79. rootPlans.extend(children)
  80. response = requests.post(SCHEDULER_BASE_URL + '/addMission', json=calculateData)
  81. print(response.json())
  82. if response.json()['code'] == 'OK':
  83. # 更新mission的运行状态
  84. mission.state = 'calculating'
  85. mission.save()
  86. return success(message="成功启动计算任务")
  87. else:
  88. return failed(message="启动计算任务失败")