forked from doylejg/flask-todo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp2.py
66 lines (49 loc) · 1.98 KB
/
app2.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
from sqlalchemy import create_engine, select, update, delete
from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
# /// = relative path, //// = absolute path
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], connect_args={"check_same_thread": False})
Session = sessionmaker(bind = engine, future = True)
Base = declarative_base(bind = engine)
class Todo(Base):
__tablename__ = 'todo_list'
id = Column(Integer, primary_key=True)
title = Column(String(100))
complete = Column(Boolean)
def __repr__(self):
return f"Todo(id={self.id!r}, title={self.title!r}, complete={self.complete!r})"
@app.route("/")
def home():
with Session() as session:
todo_list = session.execute(select(Todo)).scalars().all()
return render_template("base.html", todo_list=todo_list)
@app.route("/add", methods=["POST"])
def add():
title = request.form.get("title")
with Session() as session:
new_todo = Todo(title=title, complete=False)
session.add(new_todo)
session.commit()
return redirect(url_for("home"))
@app.route("/update/<int:todo_id>")
def update(todo_id):
with Session() as session:
todo = session.execute(select(Todo).filter_by(id=todo_id)).scalar_one()
todo.complete = not todo.complete
session.commit()
return redirect(url_for("home"))
@app.route("/delete/<int:todo_id>")
def delete(todo_id):
with Session() as session:
todo = session.execute(select(Todo).filter_by(id=todo_id)).scalar_one()
session.delete(todo)
session.commit()
return redirect(url_for("home"))
if __name__ == "__main__":
Base.metadata.create_all(engine)
app.run(debug=True)