forked from microsoft/EveryoneCanCode-US
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
177 lines (144 loc) · 5.2 KB
/
app.py
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
###############################################################################
## Sprint 7: Advanced Styling in your Web Application
## Feature 1: Advanced Web App Styling
## User Story 3: Prevent User from adding blank task and limit characters
###############################################################################
import os
import json
from flask import Flask, render_template, request, redirect, url_for, g
from database import db, Todo
from recommendation_engine import RecommendationEngine
from tab import Tab
from priority import Priority
from context_processors import inject_current_date
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__)) # Get the directory of the this file
todo_file = os.path.join(basedir, 'todo_list.txt') # Create the path to the to-do list file using the directory
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///' + os.path.join(basedir, 'todos.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
@app.context_processor
def inject_common_variables():
return inject_current_date()
with app.app_context():
db.create_all()
@app.before_request
def load_data_to_g():
todos = Todo.query.all()
g.todos = todos
g.todo = None
g.TabEnum = Tab
g.PriorityEnum = Priority
g.selectedTab = Tab.NONE
@app.route("/")
def index():
return render_template("index.html")
@app.route("/add", methods=["POST"])
def add_todo():
# Get the data from the form
todo = Todo(
name=request.form["todo"]
)
# Add the new ToDo to the list
db.session.add(todo)
db.session.commit()
# Add the new ToDo to the list
return redirect(url_for('index'))
# Details of ToDo Item
@app.route('/details/<int:id>', methods=['GET'])
def details(id):
g.selectedTab = Tab.DETAILS
g.todos = Todo.query.all()
g.todo = Todo.query.filter_by(id=id).first()
return render_template('index.html')
# Edit a new ToDo
@app.route('/edit/<int:id>', methods=['GET'])
def edit(id):
g.selectedTab = Tab.EDIT
g.todos = Todo.query.all()
g.todo = Todo.query.filter_by(id=id).first()
return render_template('index.html')
# Save existing To Do Item
@app.route('/update/<int:id>', methods=['POST'])
def update_todo(id):
g.selectedTab = Tab.DETAILS
if request.form.get('cancel') != None:
return redirect(url_for('index'))
# Get the data from the form
name = request.form['name']
due_date = request.form.get('duedate')
notes=request.form.get('notes')
priority=request.form.get('priority')
completed=request.form.get('completed')
todo = db.session.query(Todo).filter_by(id=id).first()
if todo != None:
todo.name = name
if due_date != "None":
todo.due_date = due_date
if notes != None:
todo.notes = notes
if priority != None:
todo.priority = int(priority)
if completed == None:
todo.completed = False
elif completed == "on":
todo.completed = True
#
db.session.add(todo)
db.session.commit()
#
return redirect(url_for('index'))
# Delete a ToDo
@app.route('/remove/<int:id>', methods=["POST"])
def remove_todo(id):
g.selectedTab = Tab.NONE
db.session.delete(Todo.query.filter_by(id=id).first())
db.session.commit()
return redirect(url_for('index'))
# Show AI recommendations
@app.route('/recommend/<int:id>', methods=['GET'])
@app.route('/recommend/<int:id>/<refresh>', methods=['GET'])
async def recommend(id, refresh=False):
g.selectedTab = Tab.RECOMMENDATIONS
recommendation_engine = RecommendationEngine()
g.todo = db.session.query(Todo).filter_by(id=id).first()
if g.todo and not refresh:
try:
#attempt to load any saved recommendation from the DB
if g.todo.recommendations_json is not None:
g.todo.recommendations = json.loads(g.todo.recommendations_json)
return render_template('index.html')
except ValueError as e:
print("Error:", e)
previous_links_str = None
if refresh:
g.todo.recommendations = json.loads(g.todo.recommendations_json)
# Extract links
links = [item["link"] for item in g.todo.recommendations]
# Convert list of links to a single string
previous_links_str = ", ".join(links)
g.todo.recommendations = await recommendation_engine.get_recommendations(g.todo.name, previous_links_str)
# Save the recommendations to the database
try:
g.todo.recommendations_json = json.dumps(g.todo.recommendations)
db.session.add(g.todo)
db.session.commit()
except Exception as e:
print(f"Error adding and committing todo: {e}")
return
return render_template('index.html')
@app.route('/completed/<int:id>/<complete>', methods=['GET'])
def completed(id, complete):
g.selectedTab = Tab.NONE
g.todo = Todo.query.filter_by(id=id).first()
if (g.todo != None and complete == "true"):
g.todo.completed = True
elif (g.todo != None and complete == "false"):
g.todo.completed = False
#
db.session.add(g.todo)
db.session.commit()
#
return redirect(url_for('index'))
if __name__ == "__main__":
app.run(debug=True)