-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
130 lines (119 loc) · 5.74 KB
/
Copy pathmain.py
File metadata and controls
130 lines (119 loc) · 5.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
from fastapi import FastAPI, Request, Form, Path
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
import logging, scheduler, uvicorn, executor
from typing import Optional
import threading, sqlite3
from datetime import datetime
# initialize FastAPI and Jinja2 instances
app = FastAPI()
templates = Jinja2Templates(directory="HTMLfiles")
logging.basicConfig(level=logging.INFO) #set up logging
@app.get("/")
def root(request: Request):
tasks = scheduler.get_scheduled_tasks() # Get the scheduled tasks from the scheduler
return templates.TemplateResponse("index.html",
{"request": request, "task_table": tasks}) # render index.html
@app.post("/delete/{task_id}")
async def delete_task(task_id: int = Path(...)):
scheduler.delete_task(task_id)
return RedirectResponse("/", status_code=303)
@app.post("/schedule")
async def schedule(
request: Request,
trigger_type: str = Form(...), # Gets value from name="trigger_type"
run_date: Optional[str] = Form(None), # Gets value from name="run_date"
interval_seconds: Optional[str] = Form(None), # Gets value from name="interval_seconds"
cron_hour: Optional[str] = Form(None), # Gets value from name="cron_hour"
cron_minute: Optional[str] = Form(None), # Gets value from name="cron_minute"
cron_second: Optional[str] = Form(None), # Gets value from name="cron_second"
command: str = Form(...), # Gets value from name="command"
):
try:
trigger_kwargs = {}
error_msg = None
if trigger_type == 'date':
trigger_kwargs['trigger_type'] = trigger_type
if not run_date:
raise ValueError("Run date cannot be empty for date trigger")
# strptime() will raise an error if the date format is incorrect
trigger_kwargs['run_date'] = datetime.strptime(run_date, "%Y-%m-%dT%H:%M:%S")
trigger_kwargs['interval_seconds'] = None
trigger_kwargs['cron_hour'] = None
trigger_kwargs['cron_minute'] = None
trigger_kwargs['cron_second'] = None
trigger_kwargs['last_run'] = None
if not command:
raise ValueError("Command cannot be empty for date trigger")
trigger_kwargs['command'] = command # Command to run
elif trigger_type == 'interval':
trigger_kwargs['trigger_type'] = trigger_type
trigger_kwargs['run_date'] = None
trigger_kwargs['interval_seconds'] = int(interval_seconds) # Run every interval seconds from now
trigger_kwargs['cron_hour'] = None
trigger_kwargs['cron_minute'] = None
trigger_kwargs['cron_second'] = None
trigger_kwargs['last_run'] = None
if not command:
raise ValueError("Command cannot be empty for date trigger")
trigger_kwargs['command'] = command # Command to run
elif trigger_type == 'cron':
trigger_kwargs['trigger_type'] = trigger_type
trigger_kwargs['run_date'] = None
trigger_kwargs['interval_seconds'] = None
#check for empty values and values of out range
if not cron_hour or not cron_minute or not cron_second:
raise ValueError("Cron hour, minute, and second cannot be empty for cron trigger")
if int(cron_hour) < 0 or int(cron_hour) > 23:
raise ValueError("Cron hour must be between 0 and 23")
if int(cron_minute) < 0 or int(cron_minute) > 59:
raise ValueError("Cron minute must be between 0 and 59")
if int(cron_second) < 0 or int(cron_second) > 59:
raise ValueError("Cron second must be between 0 and 59")
trigger_kwargs['cron_hour'] = int(cron_hour)
trigger_kwargs['cron_minute'] = int(cron_minute)
trigger_kwargs['cron_second'] = int(cron_second)
trigger_kwargs['last_run'] = None
if not command:
raise ValueError("Command cannot be empty for date trigger")
trigger_kwargs['command'] = command # Command to run
scheduler.schedule_task(**trigger_kwargs) #schedule task
return RedirectResponse("/", status_code=303) #redirect back to root page
except Exception as e:
# type error found, return error message and load index.html w/ error
error_msg = str(e)
tasks = scheduler.get_scheduled_tasks()
return templates.TemplateResponse("index.html", {"request": request, "task_table": tasks, "error_msg": error_msg})
if __name__ == "__main__":
# connect to SQLite DB and create the task table if it doesn't exist
with sqlite3.connect('task_db.db') as connection:
cursor = connection.cursor()
#check if the task table exists. If not, create it
create_table_query = '''
CREATE TABLE IF NOT EXISTS task_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
command TEXT,
trigger_type TEXT,
run_date TEXT,
interval_seconds INT,
last_run TEXT,
cron_hour INT,
cron_minute INT,
cron_second INT
);
'''
cursor.execute(create_table_query)
connection.commit()
#make threads for executor and uvicorn server
threads = []
# 1 Thread for executor
t_executor = threading.Thread(target=executor.run_executor)
threads.append(t_executor)
t_executor.start()
# 1 Thread for uvicorn server
t_uvicorn = threading.Thread(target=uvicorn.run, args=(app,), kwargs={"host": "127.0.0.1", "port": 8000})
threads.append(t_uvicorn)
t_uvicorn.start()
# Wait for both threads to finish
for t in threads:
t.join()