Skip to content

Instantly share code, notes, and snippets.

@vingkan
Last active November 24, 2017 17:37
Show Gist options
  • Save vingkan/3b559743ca2d8a72102eececc44853bb to your computer and use it in GitHub Desktop.
Save vingkan/3b559743ca2d8a72102eececc44853bb to your computer and use it in GitHub Desktop.
Text Files as a Database

Text Files as a Database

Try the demo at cs100flaskdemo.glitch.me

Running Locally or on Cloud9

Download the zip file here, or replace the dashes in these gist filenames with the correct directory structure. To Run:

./start.sh

If you get a permission error for this script, run:

chmod 0755 ./start.sh

Then run the script again.

Make my CS100 project awesome
<!DOCTYPE html>
<html>
<head>
<title>CS100 Project</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.min.css">
<link rel="stylesheet" href="./static/css/main.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<section class="hero section is-primary is-fullheight">
<div class="box content">
<h1 class="title is-1">To-Do List</h1>
<hr>
<ul id="list"></ul>
<input class="input" type="text">
<button class="button is-primary">Submit</button>
</div>
</section>
<script type="text/javascript" src="./static/js/main.js"></script>
</body>
</html>
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()
#!/bin/bash
# Python buffers stdout. Without this, you won't see what you "print" in the Activity Logs
export PYTHONUNBUFFERED=true
export FLASK_DEBUG=1
export FLASK_APP=server.py
flask run --port=8081 --host=0.0.0.0
.input, .button {
display: inline-block;
}
.input {
width: 300px;
}
.box {
width: 425px;
margin: 10px auto;
}
.hero.is-primary .title {
color: #4a4a4a !important;
font-weight: bold;
}
let list = document.querySelector('ul');
let input = document.querySelector('input');
let button = document.querySelector('button');
function getItemElement(text) {
let li = document.createElement('li');
li.innerHTML = `
<span>${text}</span>
<button class="delete"></button>
`;
return li;
}
function addItem(item) {
$.get('./todos/add', {
item: item
}).then(function(response) {
if(response.success) {
console.log(`Added ${item} at id: ${response.id}`);
updateList();
}
});
}
function removeItem(id) {
$.get('./todos/remove', {
id: id
}, function(response) {
if (response.success) {
console.log(`Deleted item at id: ${id}`);
updateList();
}
});
}
function updateList() {
$.get('./todos/getall').then(function(items) {
list.innerHTML = '';
for (let i = 0; i < items.length; i++) {
let entry = items[i];
let li = getItemElement(entry.item);
// Remove the item if delete button is clicked
li.querySelector('button').addEventListener('click', function(e) {
removeItem(entry.id);
});
list.appendChild(li);
}
});
}
updateList();
button.addEventListener('click', (e) => {
addItem(input.value);
input.value = '';
});
// Bonus: also add item if user hits enter key in text box
input.addEventListener('keypress', (e) => {
if (e.keyCode === 13) {
addItem(input.value);
input.value = '';
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment