Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active October 2, 2023 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/d013502a7aafc4be5d1ac95bdfff90ef to your computer and use it in GitHub Desktop.
Save code-boxx/d013502a7aafc4be5d1ac95bdfff90ef to your computer and use it in GitHub Desktop.
Python Flask Save Form Into Database

PYTHON FLASK SAVE HTML FORM INTO DATABASE

https://code-boxx.com/save-html-form-database-python-flask/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Create a templates folder, move S2_form.html inside.
    • Create a virtual environment - virtualenv venv.
    • Activate the virtual environment - venv\scripts\activate (Windows) venv/bin/activate (Mac/Linux)
    • Install Flask - pip install flask
    • Run python S3_server.py to start the server.
  2. Access http://localhost in your browser.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE dummy (
id INTEGER,
email TEXT NOT NULL,
txt TEXT NOT NULL,
PRIMARY KEY("id" AUTOINCREMENT)
);
# (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!")
<!DOCTYPE html>
<html>
<head>
<title>Save Form Into Database Demo</title>
<meta charset="utf-8">
<style>
/* (X) NOT IMPORTANT - COSMETICS */
* {
font-family: Arial, Helvetica, sans-serif;
font-size: 1em;
box-sizing: border-box;
}
div.notify {
padding: 10px;
margin-bottom: 10px;
background: #2e6a0f;
color: #fff;
}
form {
max-width: 400px;
padding: 20px;
border: 1px solid #eee;
background: #f7f7f7;
}
label, input {
display: block;
width: 100%;
}
label { padding: 10px 0; }
input { padding: 10px; }
input[type=text], input[type=email] { border: 1px solid #d1d1d1; }
input[type=submit] {
margin-top: 20px;
border: 0;
cursor: pointer;
color: #fff;
background: #515fbf;
}
</style>
</head>
<body>
{% if saved %}
<div class="notify">Saved</div>
{% endif %}
<form method="post">
<label>Email</label>
<input type="email" name="email" required value="jon@doe.com">
<label>Text</label>
<input type="text" name="txt" required value="It works!">
<input type="submit" value="Go!">
</form>
</body>
</html>
# (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
saved = False
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()
saved = True
# (B2) RENDER PAGE
return render_template("S2_form.html", saved=saved)
# (C) START
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
md templates
move S2_form.html templates
virtualenv venv
call venv\Scripts\activate
pip install flask
python S1B_create.py
python S3_server.py
mkdir -m 777 templates
mv ./S2_form.html ./templates
virtualenv venv
source "venv/bin/activate"
pip install flask
python S1B_create.py
python S3_server.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment