|
import time #Importing the time library to check the time of code execution |
|
import sys #Importing the System Library |
|
import os |
|
import socket |
|
|
|
from flask import Flask |
|
from flask import render_template |
|
from flask import jsonify |
|
from flask import request |
|
|
|
server = Flask(__name__) |
|
|
|
@server.route('/') |
|
def index(): |
|
return render_template('index.html') |
|
|
|
@server.route('/todos/getall') |
|
def getall(): |
|
items = [] |
|
with open("database/items.txt", "r") as file: |
|
lines = file.read().split("\n") |
|
for id, item in enumerate(lines): |
|
# check for items that have been removed |
|
item = str(item).strip() |
|
if item: |
|
items.append({ |
|
'id': id, |
|
'item': item |
|
}) |
|
# must use jsonify to format list properly |
|
return jsonify(items) |
|
|
|
@server.route('/todos/get') |
|
def get(): |
|
id = int(request.args.get("id")) |
|
item = None |
|
with open("database/items.txt", "r") as file: |
|
lines = file.read().split("\n") |
|
# in case id does not exist |
|
try: |
|
item = lines[id] |
|
except IndexError: |
|
item = None |
|
# in case id exists but item was removed |
|
if not item: |
|
item = None |
|
return jsonify({ |
|
'id': id, |
|
'item': item |
|
}) |
|
|
|
@server.route('/todos/add') |
|
def add(): |
|
item = request.args.get("item") |
|
# r: read the file |
|
id = 0 |
|
with open("database/items.txt", "r") as file: |
|
lines = file.read().split("\n") |
|
id = len(lines) |
|
# a: append to the file |
|
with open("database/items.txt", "a") as file: |
|
value = str(item) + "\r\n" |
|
file.write(value) |
|
return jsonify({'success': True, 'id': id}) |
|
|
|
@server.route('/todos/remove') |
|
def remove(): |
|
id = int(request.args.get("id")) |
|
val = None |
|
# r: read the file |
|
with open("database/items.txt", "r") as file: |
|
lines = file.read().split("\n") |
|
# remove the item without changing other ids |
|
lines[id] = "\r" |
|
val = "\n".join(lines) |
|
# w: write over the file |
|
with open("database/items.txt", "w") as file: |
|
file.write(val) |
|
return jsonify({'success': True}) |
|
|
|
if __name__ == "__main__": |
|
server.run() |