from flask import Flask
from flask import render_template, abort, redirect, url_for
from flask import request, g
import sqlite3
= Flask(__name__)
app
@app.route("/")
def main():
return render_template("base.html") # renders homepage
Web apps are great for allowing the public to access and interact with programs that you create.
In this tutorial, we will be using Flask to create a simple message bank that allows the user to submit a message and view messages that other people have submitted. Flask is is a web application framework written in Python that allows us to create pages that allow the user to interact with the page.
Here’s the link to my project repository for the full code: https://github.com/roberttran1/FlaskApp
The first step is to add our import statements, which include flask
and sqlite3
. We will then define a main()
function that will render our homepage. This will be the landing page when someone logs onto the website. For the homepage, I have created a file called base.html
that contains the HTML code to format the page.
The template file base.html
is shown below. On the second line, we link the file to the CSS file that formats the text. Then, we define the title and any other text on the page. The “Submit a message” and “View messages” text is hyperlinked so that the user can click on it to perform the function that is stated. Finally, there is a {% block content %}
at the end so that the submission and view pages can add their own content to this base template.
<!doctype html>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<title> A Simple Message Bank </title>
<h1> A Simple Message Bank </h1>
<a href="/submit/"> Submit a message </a>
<br>
<a href="/view/"> View messages </a>
% block content %} {% endblock %} {
Next, we will define the function for the page handling the submissions. This function will use the methods “POST” and “GET.” If either method is called, the function will render submit.html
. When “POST” is called, the function will also create a database if one does not already exist and insert the message that the user submitted into the database.
@app.route("/submit/", methods=["POST","GET"])
def submit():
if request.method == "GET":
return render_template("submit.html")
else: # performs code if method is "POST"
# creates db if doesn't exist
get_message_db() # adds message to db
insert_message(request) return render_template("submit.html", message = request.form["message"], name = request.form["name"])
We also need to define the function that allows us to view the submission. This function will use the method “GET” and will call the random_messages()
function to fetch at most five random messages from the database. Then, it will render the view.html
template with those messages added to them.
@app.route("/view/", methods=["GET"])
def view():
= random_messages(5) # gets 5 random messages to display
messages return render_template("view.html", messages=messages)
Now that we’ve defined the functions that will allow us to render the pages in our web app, let’s define the helper functions that go in them. First, we will define get_message_db
, which creates the database and table if they do not already exist and return them. The table will be named “messages” and will contain three columns: “id” (an integer), “handle” (a text string), and “message” (a text string). In either case, the output of the function would be the message database. After the table is created, the function returns the database connection object, which can be used to perform various operations on the database such as inserting, updating, and querying data.
def get_message_db():
try:
return g.message_db # checks to see if db exists
except:
= sqlite3.connect("messages_db.sqlite")
g.message_db = 'CREATE TABLE IF NOT EXISTS messages (id INTEGER, handle TEXT, message TEXT)'
cmd = g.message_db.cursor()
cursor # creates table with three columns
cursor.execute(cmd) return g.message_db
Then, we will define the function insert_message()
, which will take the request
from the form, parse it, and insert it into the database. The function will call the get_message_db()
function to retrieve the database connection. Then, the function uses the SQL INSERT command string using the name and message values extracted from the request, and the format()
method is used to insert these values. The cursor.execute() method will then execule the INSERT command. This will add additional row entries into the database. Finally, the function calls db.commit()
to commit the changes to the database.
def insert_message(request):
= get_message_db()
db = request.form['message'] # parses request to get values for table
message = request.form['name']
name = sqlite3.connect("messages_db.sqlite")
db = 'INSERT INTO messages (handle, message) VALUES(\"{0}\", \"{1}\")'.format(name, message)
cmd = db.cursor()
cursor # adds row to table
cursor.execute(cmd) db.commit()
Finally, we need to define random_messages()
, which will display a given number of messages which are randomly selected from the database. This function will return a list of messages that can then be passed to the HTML template to be iterated through and displayed. We will also close the connection to our database in this function.
def random_messages(n):
= 'SELECT * FROM messages ORDER BY RANDOM() LIMIT {0};'.format(n)
cmd = get_message_db() # fetches db
db = db.cursor()
cursor
cursor.execute(cmd)= cursor.fetchall() # fetch messages from db
rows = [(row[1],row[2]) for row in rows] # add messages to a list
messages # close connection
db.close() return messages
With these five functions and the HTML/CSS templates, we can create a functional message bank. In order to preview your flask page, run the following commands:
export FLASK_ENV=development flask run
After running, you will get and address of where to find the website. Here’s what the submission and view page could look like:
Submission Page
This is what the user will see after hitting “Submit a message.”
View Page
This is what the user will see after hitting “View messages.”