Flask Web Applications with SQLite3
Flask is a lightweight web framework in Python. It provides powerful tools for building web applications, including routing, template rendering, and integration with databases like SQLite3. It allows for the use of SQLite3 to store data manually or data read from files. Alevel often has questions where you are expected to create a web app with sqlite3 to store data and display it in a table format.
1. Library Management Example
Python Backend (main.py)
import sqlite3
import flask
app = flask.Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
db = sqlite3.connect('LIBRARY.db')
cur = db.execute("""SELECT FamilyName, GivenName, Title from
Book, Member, Loan
WHERE Book.BookID = Loan.BookID and
Member.MemberNumber = Loan.MemberNumber and
Loan.Returned = 'FALSE'""")
data = cur.fetchall()
return flask.render_template('index.html', data=data)
app.run()HTML Template (index.html):
<!DOCTYPE html>
<html>
<head>
<title>Library System</title>
</head>
<body>
<table>
<tr>
<th>Family Name</th>
<th>Given Name</th>
<th>Book Title</th>
</tr>
{% for item in data %}
<tr>
<td>{{ item[0] }}</td>
<td>{{ item[1] }}</td>
<td>{{ item[2] }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>Explanation:
- The Python code fetches unreturned loan records from the SQLite3 database and passes them to the HTML template.
- The HTML template uses Jinja2 syntax to dynamically populate a table with loan data.
2. Sanitiser Management Example
Python Backend (main.py)
import sqlite3
import flask
app = flask.Flask(__name__)
@app.route('/')
def home():
conn = sqlite3.connect('sanitisers.db')
cur = conn.cursor()
cur.execute('''SELECT product_name, active_ingredient, alcohol_based FROM sanitisers''')
data = cur.fetchall()
return flask.render_template('index.html', data=data)
@app.route('/process_form/', methods=["POST"])
def process_home():
ingredient = flask.request.form['ingredient']
conn = sqlite3.connect('sanitisers.db')
cur = conn.cursor()
cur.execute('''SELECT product_name, alcohol_based FROM sanitisers WHERE active_ingredient = ?''', (ingredient,))
sanitisers = cur.fetchall()
return flask.render_template('result.html', sanitisers=sanitisers)
app.run()HTML Template (index.html)
<!DOCTYPE html>
<html>
<head>
<title>Sanitisers</title>
</head>
<body>
<table>
<tr>
<th>Product Name</th>
<th>Active Ingredient</th>
<th>Alcohol Based</th>
</tr>
{% for item in data %}
<tr>
<td>{{ item[0] }}</td>
<td>{{ item[1] }}</td>
<td>{{ item[2] }}</td>
</tr>
{% endfor %}
</table>
<form action="/process_form/" method="POST">
<p>
Active Ingredient: <input type="text" name="ingredient">
</p>
<p>
<input type="submit" value="Search">
</p>
</form>
</body>
</html>
Explanation:
- The home route displays all sanitiser data in a table.
- A form allows users to search for sanitisers by active ingredient.
- The result is displayed using a different template, dynamically populated with matching data.
Image Upload and View Example
Python Backend (main.py)
import os
from flask import Flask, render_template, request, send_from_directory
from werkzeug.utils import secure_filename
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
if request.method == 'POST' and request.files and 'image' in request.files:
image = request.files['image']
filename = secure_filename(image.filename)
path = os.path.join('uploads', filename)
image.save(path)
with open('all.txt', 'a') as file:
file.write(filename + '\n')
return render_template('index.html', status='ok')
return render_template('index.html')
@app.route('/view')
def view():
with open('all.txt', 'r') as file:
filenames = file.readlines()
images = [filename.strip() for filename in filenames]
return render_template('view.html', images=images)
@app.route('/images/')
def get_file(filename):
return send_from_directory('uploads', filename)
app.run() Explanation:
- Import Statements:
os: Handles file system operations like creating paths.Flask: The core Flask web application class.render_template: Renders HTML templates for the web pages.request: Handles HTTP requests (e.g., POST for file uploads).send_from_directory: Serves static files like images.secure_filename: Sanitizes uploaded file names to prevent malicious uploads.- Flask Application Setup:
app = Flask(__name__)>: Initializes the Flask app.- Route:
/(Home Page) - GET Request:
- Renders the
index.htmlpage to allow users to upload an image. - POST Request:
- Checks if a file named
imageis in the request. - Saves the uploaded file in the
uploadsdirectory using a secure filename. - Appends the file name to
all.txtfor tracking. - Renders the
index.htmlpage with astatus='ok'message to indicate success. - Route:
/view(Gallery Page) - Reads the
all.txtfile, which contains the list of uploaded image filenames. - Loads all filenames into a list and passes them to the
view.htmltemplate for display. - The template renders each image in a gallery format using
<img>tags. - Route:
/images/<filename>(Serve Images) - Uses
send_from_directoryto serve image files from theuploadsdirectory. - Run the App:
app.run(): Starts the Flask development server, making the app accessible.
HTML template (index.html)
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
Image: <input name="image" type="file"><br/>
</form>
<p><a href="{{ url_for('view') }}">View</a></p>
{% if status %}
{{ status }}
{% endif %}
</body>
</html>Explanation:
- Purpose:
- Provides the interface for image uploads.
- Structure:
- A form with
method="post"andenctype="multipart/form-data"allows file uploads. - A file input field named image accepts image uploads.
- A link (<code><a href="{{ url_for('view') }}">View</a></code>) leads to the gallery page.
- If
statusis set, it displays the upload status.
HTML template (view.html)
<!DOCTYPE html>
<html>
<head>
<title>View</title>
</head>
<body>
{% for image in images %}
<img src="{{ url_for('get_file', filename=image) }}" alt="{{ image }}">
{% endfor %}
<p><a href="{{ url_for('home') }}">Home</a></p>
</body>
</html>Explanation:
- Purpose:
- Displays uploaded images in a gallery.
- Structure:
- Iterates through the
imageslist (passed from the/viewroute). - Renders an
<img>tag for each filename, usingurl_forto generate the file URL dynamically. - A link (
<a href="{{ url_for('home') }}">Home</a>) leads back to the home page.