-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
77 lines (63 loc) · 1.96 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
from flask import Flask, jsonify, request
from flask_cors import CORS
import sqlite3
app = Flask(__name__)
CORS(app)
@app.before_first_request
def create_tables():
conn = sqlite3.connect('tasks.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
description TEXT,
done BOOLEAN
)""")
conn.commit()
conn.close()
@app.before_first_request
def add_tasks():
conn = sqlite3.connect('tasks.db')
c = conn.cursor()
c.execute("SELECT * FROM tasks")
tasks = c.fetchall()
if len(tasks) == 0:
c.execute("INSERT INTO tasks (description, done) VALUES (?, ?)", ("Learn Python", 0))
c.execute("INSERT INTO tasks (description, done) VALUES (?, ?)", ("Learn Flask", 0))
c.execute("INSERT INTO tasks (description, done) VALUES (?, ?)", ("Learn SQL", 0))
conn.commit()
conn.close()
@app.route("/")
def hello():
return "Hello World!"
@app.route("/tasks")
def tasks():
conn = sqlite3.connect('tasks.db')
c = conn.cursor()
c.execute("SELECT * FROM tasks")
tasks = c.fetchall()
tasks_as_objects = []
for task in tasks:
tasks_as_objects.append({
"id": task[0],
"description": task[1],
"done": task[2]
})
return jsonify(tasks_as_objects)
@app.route("/add", methods=["POST"])
def add():
conn = sqlite3.connect('tasks.db')
c = conn.cursor()
c.execute("INSERT INTO tasks (description, done) VALUES (?, ?)", (request.form["description"], 0))
conn.commit()
conn.close()
return jsonify({"id": c.lastrowid})
@app.route("/update", methods=["POST"])
def update():
conn = sqlite3.connect('tasks.db')
c = conn.cursor()
c.execute("UPDATE tasks SET description = ?, done = ? WHERE id = ?", (request.form["description"], request.form["done"], request.form["id"]))
conn.commit()
conn.close()
return "OK"
if __name__ == "__main__":
app.run()