Я пытаюсь изменить способ, которым приложение Function Function включает наши виртуальные машины Azure в нашей Envrizment. Бэкэнд в Python и передняя часть находится в Vue/JS/Bulma. Я хочу изменить одну кнопку, которая в настоящее время «добавляет расписание». Вместо этого я хочу, чтобы кнопка сказала, что включите и при нажатии, виртуальная машина включается и выключается автоматически через 8 часов. -demand. < /p>
Вот код Python, который ответственен за установку расписания.from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
import json
import logging
import utilities
schedule_bp = func.Blueprint()
def generateCronSchedule(vmData, timeString):
# Create stop time chunk
stopScheduleMinHour = (
f"{vmData[timeString].split(':')[1]} {vmData[timeString].split(':')[0]}"
)
# Create days chunk
daysString = ""
for i in range(1, 8):
if vmData["daysOfWeek"][utilities.daysMapping]:
daysString += f"{i},"
daysString = daysString.rstrip(daysString[-1])
# Extract subscription id and resource group from vm id
subscriptionId = vmData["id"].split("/")[2]
resourceGroup = vmData["id"].split("/")[4]
vmName = vmData["id"].split("/")[8]
# Check the method type to see if we're adding or deleting a schedule
if req.method == "DELETE":
logging.info("REMOVING SCHEDULE")
# Calculate updated tags
tags = {}
if vmInstance.tags:
tags = vmInstance.tags
tags.pop(utilities.STARTSCHEDULETAG, None)
tags.pop(utilities.STOPSCHEDULETAG, None)
else:
tags = {}
if vmInstance.tags:
tags = vmInstance.tags
return func.HttpResponse("OK")
< /code>
Вот код для кода Startstop: < /p>
import azure.functions as func
from azure.mgmt.compute import ComputeManagementClient
from azure.identity import DefaultAzureCredential
from croniter import croniter
import datetime
import logging
import pytz
import utilities
# Get the set timezone
current_timezone = utilities.get_setting("Timezone")
if not current_timezone:
# Default to UTC if the user hasn't set a timezone
current_timezone = "UTC"
current_time = datetime.datetime.now(pytz.timezone(current_timezone))
logging.info(f"Evaluating start/stop at {current_time}")
for subscription in utilities.get_subscriptions():
for vm in compute_client.virtual_machines.list_all():
logging.info(vm.id)
if vm.tags and utilities.STOPSCHEDULETAG in vm.tags:
stop_schedule = croniter(vm.tags[utilities.STOPSCHEDULETAG]).expanded
# Start and stop tag pair behaviour
if utilities.STARTSCHEDULETAG in vm.tags:
start_schedule = croniter(
vm.tags[utilities.STARTSCHEDULETAG]
).expanded
# Are we in an on-day?
if (
current_time.weekday() + 1 in start_schedule[4]
or start_schedule[4][0] == "*"
):
logging.info(f"[{vm.name}]: has on schedule today")
# Are we after the start time?
# [[0], [9], ['*'], ['*'], ['*']]
start_time = datetime.time(
start_schedule[1][0], start_schedule[0][0], 0
)
stop_time = datetime.time(
stop_schedule[1][0], stop_schedule[0][0], 0
)
logging.info(f"[{vm.name}]: start time {start_time}")
logging.info(f"[{vm.name}]: stop time {stop_time}")
# Get the current VM state
vm_state = utilities.extract_vm_state(vm, compute_client)
logging.info(f"[{vm.name}]: {vm_state}")
# Check what the target state of the vm should be, current vm states running/deallocating/deallocated
if (
current_time.time() > start_time
and current_time.time() < stop_time
):
logging.info(f"[{vm.name}]: VM should be running")
if vm_state != "running":
utilities.log_vm_event(vm, "starting")
events.append(utilities.set_vm_state('started', vm, compute_client))
logging.info(
f"[{vm.name}]: starting..."
)
else:
logging.info(f"[{vm.name}]: VM should be stopped")
if vm_state == "running":
utilities.log_vm_event(vm, "stopping")
events.append(utilities.set_vm_state('stopped', vm, compute_client))
logging.info(
f"[{vm.name}]: stopping..."
)
else:
logging.info(f"[{vm.name}]: is not scheduled to be on today")
# Stop tag only behaviour
else:
stop_schedule = croniter(
vm.tags[utilities.STOPSCHEDULETAG]
).expanded
# Are we in an on-day?
if (
current_time.weekday() + 1 in stop_schedule[4]
or stop_schedule[4][0] == "*"
):
stop_time = datetime.time(
stop_schedule[1][0], stop_schedule[0][0], 0
)
if current_time.time() > stop_time:
vm_state = utilities.extract_vm_state(vm, compute_client)
if vm_state == "running":
events.append(utilities.set_vm_state('stopped', vm, compute_client))
logging.warning(
f"[{vm.name}]: stopping..."
)
else:
logging.warning(
f"[{vm.name}]: is not scheduled to be stopped today"
)
# Wait for all events to complete
for event in events:
event.wait()
Прямо сейчас, когда вы нажимаете «Добавить расписание», он поднимает страницу, которая является компонентом VUE ... Вот код для него:
export default {
props: ["vm"],
emits: ["applied"],
watch: {
vm: function (newVal) {
this.vmData = newVal;
},
vmData: {
handler: function (newVal) {
let errors = [];
if (newVal.stopTime == null) {
errors.push("Schedule requires a stop time");
} else {
// Check if at least one day is defined
let dayCount = 0;
Object.keys(newVal.daysOfWeek).forEach(function (value) {
if (newVal.daysOfWeek[value]) {
dayCount += 1;
}
});
if (dayCount == 0) {
errors.push("Schedule requires at least 1 day set");
}
// Check if start date is before end date
if (newVal.startTime && newVal.stopTime) {
if (timeToDate(newVal.startTime) >= timeToDate(newVal.stopTime)) {
errors.push("Start time should be before stop time");
} else if (timeToDate(newVal.stopTime) - timeToDate(newVal.startTime) < 1800000) {
errors.push("Schedule should be at least 30 minutes long")
}
}
}
this.formErrors = errors;
},
deep: true,
},
},
mounted() {
// Make a deep copy of this
this.vmData = JSON.parse(JSON.stringify(this.vm));
// Work out if it's an empty schedule
if (!this.vm.stopTime) {
this.emptySchedule = true;
} else {
this.emptySchedule = false;
}
},
methods: {
clearStartTime: function () {
this.vmData.startTime = null;
},
removeSchedule: function () {
this.formDisabled = true;
let headers = new Headers({
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
});
import UpdateSettings from './components/UpdateSettings.vue'
import UserMessage from './components/UserMessage.vue'
import SignUp from './components/SignUp.vue'
Я пытаюсь изменить способ, которым приложение Function Function включает наши виртуальные машины Azure в нашей Envrizment. Бэкэнд в Python и передняя часть находится в Vue/JS/Bulma. Я хочу изменить одну кнопку, которая в настоящее время «добавляет расписание». Вместо этого я хочу, чтобы кнопка сказала, что включите и при нажатии, виртуальная машина включается и выключается автоматически через 8 часов. -demand. < /p> Вот код Python, который ответственен за установку расписания.from azure.identity import DefaultAzureCredential from azure.mgmt.compute import ComputeManagementClient import json import logging import utilities
schedule_bp = func.Blueprint()
def generateCronSchedule(vmData, timeString): # Create stop time chunk stopScheduleMinHour = ( f"{vmData[timeString].split(':')[1]} {vmData[timeString].split(':')[0]}" ) # Create days chunk daysString = "" for i in range(1, 8): if vmData["daysOfWeek"][utilities.daysMapping[i]]: daysString += f"{i}," daysString = daysString.rstrip(daysString[-1])
# Extract subscription id and resource group from vm id subscriptionId = vmData["id"].split("/")[2] resourceGroup = vmData["id"].split("/")[4] vmName = vmData["id"].split("/")[8]
# Check the method type to see if we're adding or deleting a schedule if req.method == "DELETE": logging.info("REMOVING SCHEDULE") # Calculate updated tags tags = {} if vmInstance.tags: tags = vmInstance.tags tags.pop(utilities.STARTSCHEDULETAG, None) tags.pop(utilities.STOPSCHEDULETAG, None) else:
tags = {} if vmInstance.tags: tags = vmInstance.tags
return func.HttpResponse("OK") < /code> Вот код для кода Startstop: < /p> import azure.functions as func from azure.mgmt.compute import ComputeManagementClient from azure.identity import DefaultAzureCredential from croniter import croniter import datetime import logging import pytz import utilities
# Get the set timezone current_timezone = utilities.get_setting("Timezone") if not current_timezone: # Default to UTC if the user hasn't set a timezone current_timezone = "UTC"
current_time = datetime.datetime.now(pytz.timezone(current_timezone)) logging.info(f"Evaluating start/stop at {current_time}")
for subscription in utilities.get_subscriptions():
for vm in compute_client.virtual_machines.list_all(): logging.info(vm.id)
if vm.tags and utilities.STOPSCHEDULETAG in vm.tags: stop_schedule = croniter(vm.tags[utilities.STOPSCHEDULETAG]).expanded # Start and stop tag pair behaviour if utilities.STARTSCHEDULETAG in vm.tags: start_schedule = croniter( vm.tags[utilities.STARTSCHEDULETAG] ).expanded # Are we in an on-day? if ( current_time.weekday() + 1 in start_schedule[4] or start_schedule[4][0] == "*" ): logging.info(f"[{vm.name}]: has on schedule today") # Are we after the start time? # [[0], [9], ['*'], ['*'], ['*']] start_time = datetime.time( start_schedule[1][0], start_schedule[0][0], 0 ) stop_time = datetime.time( stop_schedule[1][0], stop_schedule[0][0], 0 ) logging.info(f"[{vm.name}]: start time {start_time}") logging.info(f"[{vm.name}]: stop time {stop_time}") # Get the current VM state vm_state = utilities.extract_vm_state(vm, compute_client) logging.info(f"[{vm.name}]: {vm_state}") # Check what the target state of the vm should be, current vm states running/deallocating/deallocated if ( current_time.time() > start_time and current_time.time() < stop_time ): logging.info(f"[{vm.name}]: VM should be running") if vm_state != "running": utilities.log_vm_event(vm, "starting") events.append(utilities.set_vm_state('started', vm, compute_client)) logging.info( f"[{vm.name}]: starting..." ) else: logging.info(f"[{vm.name}]: VM should be stopped") if vm_state == "running": utilities.log_vm_event(vm, "stopping") events.append(utilities.set_vm_state('stopped', vm, compute_client)) logging.info( f"[{vm.name}]: stopping..." ) else: logging.info(f"[{vm.name}]: is not scheduled to be on today") # Stop tag only behaviour else: stop_schedule = croniter( vm.tags[utilities.STOPSCHEDULETAG] ).expanded # Are we in an on-day? if ( current_time.weekday() + 1 in stop_schedule[4] or stop_schedule[4][0] == "*" ): stop_time = datetime.time( stop_schedule[1][0], stop_schedule[0][0], 0 ) if current_time.time() > stop_time: vm_state = utilities.extract_vm_state(vm, compute_client) if vm_state == "running": events.append(utilities.set_vm_state('stopped', vm, compute_client)) logging.warning( f"[{vm.name}]: stopping..." ) else: logging.warning( f"[{vm.name}]: is not scheduled to be stopped today" )
# Wait for all events to complete for event in events: event.wait()
Прямо сейчас, когда вы нажимаете «Добавить расписание», он поднимает страницу, которая является компонентом VUE ... Вот код для него:
export default { props: ["vm"], emits: ["applied"], watch: { vm: function (newVal) { this.vmData = newVal; }, vmData: { handler: function (newVal) { let errors = []; if (newVal.stopTime == null) { errors.push("Schedule requires a stop time"); } else { // Check if at least one day is defined let dayCount = 0; Object.keys(newVal.daysOfWeek).forEach(function (value) { if (newVal.daysOfWeek[value]) { dayCount += 1; } }); if (dayCount == 0) { errors.push("Schedule requires at least 1 day set"); } // Check if start date is before end date if (newVal.startTime && newVal.stopTime) { if (timeToDate(newVal.startTime) >= timeToDate(newVal.stopTime)) { errors.push("Start time should be before stop time"); } else if (timeToDate(newVal.stopTime) - timeToDate(newVal.startTime) < 1800000) { errors.push("Schedule should be at least 30 minutes long") } } } this.formErrors = errors; }, deep: true, }, }, mounted() { // Make a deep copy of this this.vmData = JSON.parse(JSON.stringify(this.vm)); // Work out if it's an empty schedule if (!this.vm.stopTime) { this.emptySchedule = true; } else { this.emptySchedule = false; } }, methods: { clearStartTime: function () { this.vmData.startTime = null; }, removeSchedule: function () { this.formDisabled = true;
let headers = new Headers({ Accept: "application/json, text/plain, */*", "Content-Type": "application/json", });
import UpdateSettings from './components/UpdateSettings.vue' import UserMessage from './components/UserMessage.vue' import SignUp from './components/SignUp.vue'
Я пытаюсь изменить способ, которым приложение Function Function включает наши виртуальные машины Azure в нашей Envrizment. Бэкэнд в Python и передняя часть находится в Vue/JS/Bulma. Я хочу изменить одну кнопку, которая в настоящее время «добавляет...
Я новичок в Vue 3, и я хотел бы задать вопрос более опытным разработчикам. Когда вы разрабатываете линейную страницу, вы пишете CSS и HTML непосредственно в файлах .vue с использованием кода VS? Или вы используете какие-то визуальные инструменты для...
Я новичок в Vue 3, и я хотел бы задать вопрос более опытным разработчикам. Когда вы разрабатываете линейную страницу, вы пишете CSS и HTML непосредственно в файлах .vue с использованием кода VS? Или вы используете какие-то визуальные инструменты для...
У меня есть вакансии фронтенд-веб-разработчика, хорошие навыки реагирования.
Контакт/whatsapp: 7517957463
Я активно ищу вакансию фронтенд-разработчика. конечный разработчик, я устал, я подаю заявку через Google, Linkdin, Glassdoor, Noukari, но никто...
Я использую mysql для моего db, Spring для моего бэкэнда и angular для моего блюда. Мой фронт - это бросает эту странную ошибку, когда его правильно маршрутируется: нажмите здесь, чтобы увидеть его
Как вы видите, путь в конце IS %7bid %7d (выглядит...