Hello, I’m using django 2.2 and in my view I have two functions that do the same thing but only one element changes. I would like to try to improve my code so that I don’t repeat the same thing more times, basically do what the vm_schedule_power_on_vm
function does and
vm_schedule_power_off_vm
into one function. The only thing that will change is the call of vmware_poweron
in the vm_schedule_power_on_vm
function and vmware_poweroff
in the vm_schedule_power_off_vm
function.
path('vm/schedule/<int:pk>/powered_on/', vm.vm_schedule_power_on_vm,
name='vm_schedule_power_on_vm'),
path('vm/schedule/<int:pk>/powered_off/', vm.vm_schedule_power_off_vm,
name='vm_schedule_power_off_vm')
def vm_schedule_power_on_vm(request, pk):
sch = VmSchedule.objects.get(pk=pk)
mylistvm, mylist = list(), list()
mydate = time.strftime("%d/%m/%Y")
for i in sch.vms.all():
if i.lock:
return 'locked'
# here the order has importance because
#I try to have the have start time and at the end the end time.
mylist.append(mydate)
mylist.append(time.strftime("%H:%M:%S"))
mylist.append(i.name)
mylist.append(i.vmware.hostname)
# only this line changes each time
mylist.append(vmware_poweron(i))
mylist.append(time.strftime("%H:%M:%S"))
mylist.append(sch.schedule)
mylistvm.append(mylist)
mylist = list()
vm_logs_export(mylistvm)
return HttpResponse(json.dumps(mylistvm))
def vm_schedule_power_off_vm(request, pk):
sch = VmSchedule.objects.get(pk=pk)
mylistvm, mylist = list(), list()
mydate = time.strftime("%d/%m/%Y")
for i in sch.vms.all():
if i.lock:
return 'locked'
mylist.append(mydate)
mylist.append(time.strftime("%H:%M:%S"))
mylist.append(i.name)
mylist.append(i.vmware.hostname)
# only this line changes each time
mylist.append(vmware_poweroff(i))
mylist.append(time.strftime("%H:%M:%S"))
mylist.append(sch.schedule)
mylistvm.append(mylist)
mylist = list()
vm_logs_export(mylistvm)
return HttpResponse(json.dumps(mylistvm))
# Example result of vm_schedule_power_on_vm or vm_schedule_power_off_vm
['09/12/2021', '13:54:33', 'API1VTEST11', 'ste1vvcsa', '13:54:33', 'testPowredOn02', '09/12/2021', '13:54:33', 'API1VTEST12', 'ste1vvcsa', '13:54:33', 'testPowredOn02', '09/12/2021', '13:54:33', 'API1VTEST2', 'ste1vvcsa', '13:54:33'
, 'testPowredOn02']
#
def vmware_poweron(vm):
#return list of something
def vmware_poweroff(vm):
#return list of something
# Example result of vmware_poweron or vmware_poweroff
[["09/12/2021", "13:54:33", "API1VTEST11", "ste1vvcsa", "13:54:33", "testPowredOn02", "09/12/2021", "13:54:33", "API1VTEST12", "ste1vvcsa", "13:54:33", "testPowredOn02", "09/12/2021", "13:54:33", "API1VTEST2", "ste1vvcsa", "13:54:33", "testPowredOn02"]