Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active October 7, 2023 13:23
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/502298c7308393167b9249ebeec23fbe to your computer and use it in GitHub Desktop.
Save code-boxx/502298c7308393167b9249ebeec23fbe to your computer and use it in GitHub Desktop.
Python Flask Search & Display Results

PYTHON FLASK SEARCH & DISPLAY RESULTS

https://code-boxx.com/search-results-python-flask/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Create a templates folder, move S3_users.html inside.
    • Create a static folder, move S3_users.css 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
    • Create the dummy database - python S1B_create.py
    • Run python S2_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.

-- (A) USERS TABLE
CREATE TABLE users (
uid INTEGER,
name TEXT NOT NULL,
email TEXT NOT NULL,
tel TEXT NOT NULL,
PRIMARY KEY("uid" AUTOINCREMENT)
);
CREATE INDEX `idx_name`
ON `users` (`name`);
CREATE UNIQUE INDEX `idx_email`
ON `users` (`email`);
-- (B) DUMMY DATA
INSERT INTO "users" VALUES
(1,'Jo Doe','jo@doe.com','465785'),
(2,'Joa Doe','joa@doe.com','123456'),
(3,'Job Doe','job@doe.com','234567'),
(4,'Joe Doe','joe@doe.com','345678'),
(5,'Jog Doe','jog@doe.com','578456'),
(6,'Joh Doe','joh@doe.com','378945'),
(7,'Joi Doe','joi@doe.com','456789'),
(8,'Jon Doe','jon@doe.com','987654'),
(9,'Jor Doe','jor@doe.com','754642'),
(10,'Joy Doe','joy@doe.com','124578');
# (A) LOAD PACKAGES
import sqlite3, os
from sqlite3 import Error
# (B) DATABASE + SQL FILE
DBFILE = "users.db"
SQLFILE = "S1A_users.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!")
# (A) INIT
# (A1) LOAD MODULES
from flask import Flask, render_template, request, make_response
import sqlite3
# (A2) FLASK SETTINGS + INIT
HOST_NAME = "localhost"
HOST_PORT = 80
DBFILE = "users.db"
app = Flask(__name__)
# app.debug = True
# (B) HELPER FUNCTION - SEARCH USERS
def getusers(search):
conn = sqlite3.connect(DBFILE)
cursor = conn.cursor()
cursor.execute(
"SELECT * FROM `users` WHERE `name` LIKE ? OR `email` LIKE ?",
("%"+search+"%", "%"+search+"%",)
)
results = cursor.fetchall()
conn.close()
return results
# (C) DEMO SEARCH PAGE
@app.route("/", methods=["GET", "POST"])
def index():
# (C1) SEARCH FOR USERS
if request.method == "POST":
data = dict(request.form)
users = getusers(data["search"])
else:
users = []
# (C2) RENDER HTML PAGE
return render_template("S3_users.html", usr=users)
# (D) START
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
* {
font-family: arial, sans-serif;
box-sizing: border-box;
}
body {
width: 300px;
}
form {
padding: 10px;
border: 1px solid #e5e5e5;
background: #f5f5f5;
display: flex;
align-items: center;
}
input {
padding: 10px;
border: 0;
}
input[type=text] { flex-grow: 1; }
input[type=submit] {
color: #fff;
background: #4566e1;
cursor: pointer;
}
#demo {
margin-top: 10px;
width: 100%;
}
table#demo {
border: 1px solid #e5e5e5;
border-collapse: collapse;
}
table#demo tr td {
padding: 10px;
}
table#demo tr:nth-child(odd) {
background: #f2f2f2;
}
<!DOCTYPE html>
<html>
<head>
<title>Search Users</title>
<link rel="stylesheet" href="static/S3_users.css">
</head>
<body>
<!-- (A) SEARCH FORM -->
<form method="post">
<input type="text" name="search" required>
<input type="submit" value="Search">
</form>
<!-- (B) OUTPUT SEARCH RESULTS -->
{% if usr | length != 0 %}
<table id="demo">
{% for u in usr %}
<tr>
<td>{{ u[0] }}</td>
<td>{{ u[1] }}</td>
<td>{{ u[2] }}</td>
</tr>
{% endfor %}
</table>
{% else %}
<div id="demo">No search results.</div>
{% endif %}
</body>
</html>
md templates
md static
move S3_users.html templates
move S3_users.css static
virtualenv venv
call venv\Scripts\activate
pip install flask
python S1B_create.py
python S2_server.py
mkdir -m 777 templates
mkdir -m 777 static
mv ./S3_users.html ./templates
mv ./S3_users.css ./static
virtualenv venv
source "venv/bin/activate"
pip install flask
python S1B_create.py
python S2_server.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment