Flask based web applications
We will build a student attendance app. Student will have to come to this app enter their name and the app will record their name, IP address and the time they submitted the form
We will not worry about cases such as:
First we need the DB to store all the students
We will use the SQLite
We will not worry about cases such as:
- Same user submitting the form multiple times
- Students submitting the form for others (although we have the IP address ;-)
First we need the DB to store all the students
We will use the SQLite
import sqlite3 conn = sqlite3.connect("students.sqlite") cursor = conn.cursor() cursor.execute("create table students (name text, ip text, submitted datetime)") conn.commit() conn.close()
Run it, and this is what my directory looks like right now:
Now, we will create the student submit form in Flask
index.html template:
index.html template:
<title>Attendance Sheet</title> {% if name %} <h1>Thank you, {{ name }}, your attendance has been recorded!</h1> {% else %} <h1> <br/> <form> Your Name:<input type="text" name = "name"> <br> <input type='submit' name='Submit' > </form> </h1> {% endif %}
Flask app flask_app.py:
from flask import Flask,request, abort from flask import render_template app=Flask(__name__) @app.route('/') def attendance(): name = request.args.get('name', '') return render_template('index.html', name=name) app.run(debug = True)
And this is what we get:
Now we store it to the DB:
from flask import Flask,request, abort from flask import render_template import sqlite3 from datetime import datetime app=Flask(__name__) @app.route('/') def attendance(): name = request.args.get('name', None) if name: store_to_db(name=name, ip=request.remote_addr, time=datetime.now()) return render_template('index.html', name=name) def store_to_db(name=None, time=None, ip=None): conn = sqlite3.connect("students.sqlite") cursor = conn.cursor() cursor.execute("insert into students(name, ip, submitted) values(?, ?, ?)", (name, ip, time)) conn.commit() conn.close() app.run(debug = True)
- Build an endpoint that will list all student attendance records in the DB
- Build an endpoint that will list all student attendance records in the DB organized by day