7. User Interface ‐ Flask - jcmwright80/work-experience GitHub Wiki
In this final tutorial we will show you how to create a simple user interface (UI) for your app which should display your list of TODO's and allow you to add more. To do this we will use python flask which is a lightweight Python web framework which we already installed in a previous step.
Step 1. Create app.py at the base of your app with the following content:
from flask import Flask, request, render_template_string
from db import get_connection
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
task = request.form["task"]
conn = get_connection()
cur = conn.cursor()
cur.execute("INSERT INTO todos (task) VALUES (%s)", (task,))
conn.commit()
conn.close()
conn = get_connection()
cur = conn.cursor()
cur.execute("SELECT id, task FROM todos")
todos = cur.fetchall()
conn.close()
return render_template_string("""
<form method="post">
<input name="task"/>
<button>Add</button>
</form>
<ul>
{% for id, task in todos %}
<li>{{ task }}</li>
{% endfor %}
</ul>
""", todos=todos)
if __name__ == "__main__":
app.run(debug=True)