Welcome to a tutorial on how to save an HTML form into the database with Python Flask and SQLite. Just started with Python Flask and want to save a submitted form into the database? Well, it actually pretty easy – Read on for an example!
ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
TLDR – QUICK SLIDES
Fullscreen Mode – Click Here
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
- Create a project folder, e.g.
D:\save, unzip the code inside this folder.
- Navigate to the project folder in the command line
cd D:\save, create a virtual environment to not mess up your other projects.
- Windows –
- Mac/Linux –
- Get all the packages –
pip install flask
- Create the database
python S3_server.pyand access
EXAMPLE CODE DOWNLOAD
Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
PYTHON FLASK SAVE HTML FORM
All right, let us now get into the details of creating a simple star rating system with Python Flask and SQLite.
STEP 1) THE DATABASE
1A) DUMMY DATABASE TABLE
CREATE TABLE dummy ( id INTEGER, email TEXT NOT NULL, txt TEXT NOT NULL, PRIMARY KEY("id" AUTOINCREMENT) );
Let us start with a dummy database to work with, just a very simple one with 3 fields.
idPrimary key, auto-increment.
txtWhatever random text/content.
1B) CREATE THE DATABASE
# (A) LOAD PACKAGES import sqlite3, os from sqlite3 import Error # (B) DATABASE + SQL FILE DBFILE = "dummy.db" SQLFILE = "S1A_dummy.sql" # (C) DELETE OLD DATABASE IF EXIST if os.path.exists(DBFILE): os.remove(DBFILE) # (D) IMPORT SQL conn = sqlite3.connect(DBFILE) with open(SQLFILE) as f: conn.executescript(f.read()) conn.commit() conn.close() print("Database created!")
Next, this should be self-explanatory – We read the SQL file and create the actual database itself.
STEP 2) HTML FORM
<form method="post"> <label>Email</label> <input type="email" name="email" required value="email@example.com"> <label>Text</label> <input type="text" name="txt" required value="It works!"> <input type="submit" value="Go!"> </form>
Don’t think this needs much explanation… Just a “regular Joe” HTML form.
STEP 3) FLASK SERVER
# (A) INIT # (A1) LOAD MODULES from flask import Flask, render_template, request import sqlite3 # (A2) FLASK SETTINGS + INIT HOST_NAME = "localhost" HOST_PORT = 80 app = Flask(__name__) # app.debug = True # (B) DUMMY PAGE @app.route("/", methods=["GET", "POST"]) def index(): # (B1) SAVE ON FORM SUBMIT if request.method == "POST": conn = sqlite3.connect("dummy.db") cursor = conn.cursor() cursor.execute("INSERT INTO dummy (`email`, `txt`) VALUES (?,?)", (request.values.get("email"), request.values.get("txt"))) conn.commit() conn.close() # (B2) RENDER PAGE return render_template("S2_form.html") # (C) START if __name__ == "__main__": app.run(HOST_NAME, HOST_PORT)
- Load the required modules (Flask and SQLite), plus a bunch of settings.
- Take note of how this works.
- (B2) When “accessed normally”, we serve the above HTML form.
- (B1) When the form is submitted, we save it into the database.
- Start the Flask server.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
A FEW MORE NOTES
Yes, saving an HTML form is that simple, but a couple of things to take note of:
- SQLite is a great tool for learning, but it is better to use a “professional database” for production servers.
- PostgreSQL, MySQL, Redis, or MongoDB – Pick your poison. Best to learn at least one.
- To show a saved/error message in the HTML, we can pass variables into the template. A quick pseudo-code snippet:
message = ""
try: SAVE INTO DATABASE, THEN message = "OK"
except: message = "ERROR MESSAGE"
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEET
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!