Welcome to a tutorial on how to create a simple tags system with Python Flask. Want to dynamically add tags to your audio, video, photo, post, product, or whatever it is? Well, here’s a quick example that I have made for beginners – Read on!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
PYTHON FLASK TAGS
All right, let us now get into the details of creating a simple tagging system with Python Flask and SQLite.
QUICK SETUP
- Create a virtual environment
virtualenv venv
and activate it –venv\Scripts\activate
(Windows)venv/bin/activate
(Linux/Mac) - Install required libraries –
pip install flask
- For those who are new, the default Flask folders are –
static
Public files (JS/CSS/images/videos/audio)templates
HTML pages
STEP 1) THE DATABASE
1A) TAGS TABLE
-- (A) TAGS TABLE
CREATE TABLE `tags` (
`content_id` INTEGER NOT NULL,
`tag_name` TEXT NOT NULL
);
CREATE INDEX idx_tags_name
ON tags (content_id, tag_name);
-- (C) DUMMY DATA
INSERT INTO `tags`
(`content_id`, `tag_name`)
VALUES
(999, "Food"),
(999, "Meat"),
(999, "Spicy"),
(999, "Main");
For the first step, we will start by creating a very simple tags
table. This should be self-explanatory.
content_id
The audio/video/photo/content that you want to tag.tag_name
The attached tags.
1B) CREATE THE DATABASE
# (A) LOAD PACKAGES
import sqlite3, os
from sqlite3 import Error
# (B) DATABASE + SQL FILE
DBFILE = "tags.db"
SQLFILE = "S1A_tags.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, we simply create a tags database and import the above SQL file.
STEP 2) TAGS LIBRARY MODULE
# (A) LOAD SQLITE MODULE
import sqlite3
DBFILE = "tags.db"
# (B) HELPER - RUN SQL QUERY
def query(sql, data):
conn = sqlite3.connect(DBFILE)
cursor = conn.cursor()
cursor.execute(sql, data)
conn.commit()
conn.close()
# (C) HELPER - FETCH ALL
def select(sql, data=[]):
conn = sqlite3.connect(DBFILE)
cursor = conn.cursor()
cursor.execute(sql, data)
results = cursor.fetchall()
conn.close()
return results
# (D) GET TAGS FOR CONTENT
# cid : content id
def get(cid):
res = []
for row in select("SELECT `tag_name` FROM `tags` WHERE `content_id`=?", [cid]):
res.append(row[0])
return res
# (E) DELETE TAGS
# cid : content id
def delete(cid):
query("DELETE FROM `tags` WHERE `content_id`=?", [cid])
return True
# (F) SAVE TAGS
# cid : content id
# tags : array of tags
def save(cid, tags):
# (F1) DELETE OLD TAGS
delete(cid)
# (F2) INSERT NEW TAGS
sql = "INSERT INTO `tags` (`content_id`, `tag_name`) VALUES "
data = []
for tag in tags:
sql = sql + "(?,?),"
data.extend([cid, tag])
sql = sql[:-1] + ";"
query(sql, data)
return True
With the database in place, we now create a library to work with it. This may look complicated at first, but keep calm and look closely.
- Use the SQLite module. Captain Obvious at your service.
query()
Helper function to run an SQL query.fetch()
Helper function to run a SQLSELECT
.get()
Get all tags for the given content ID.delete()
Delete all tags for the given content ID.save()
Update the list of tags for the given content ID.
Yep. That’s all. Feel free to expand on this library, maybe add a “search content by tag name” function.
STEP 3) FLASK SERVER
# (A) INIT
# (A1) LOAD MODULES
from flask import Flask, render_template, request, make_response
import S2_lib as tagger
# (A2) FLASK SETTINGS + INIT
HOST_NAME = "localhost"
HOST_PORT = 80
app = Flask(__name__)
# app.debug = True
# (A3) FIXED CONTENT ID FOR THIS DEMO
cid = 999
# (B) FEEDBACK HTML PAGE
@app.route("/")
def index():
# (B1) GET CONTENT TAGS
tags = tagger.get(cid)
# (B2) RENDER HTML PAGE
return render_template("S4_tags.html", tags=tags)
# (C) START
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
Not going to explain this line-by-line once again, but the Flask server script is very straightforward. We simply get the tags from the database and pass them into the HTML template.
STEP 4) HTML PAGE
<div class="pTags">
{% for t in tags %}
<div class="tag">{{ t }}</div>
{% endfor %}
</div>
Loop through the tags, and output them in HTML. The end.
EXTRAS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
A STARTING POINT
Of course, this is only a barebones example, a starting point. There are a lot of things that you can build on top of it:
- Add an admin panel to manage the tags (add/update/delete tags to content).
- Not a good idea to use SQLite for live systems, see below.
- Add your own “search by tag” feature –
SELECT `content_id` from `tags` WHERE `tag_name` LIKE ?
Everyone has different requirements, so it is up to you to complete your own system now.
SQLITE IS NO GOOD FOR LIVE SYSTEMS
Before the angry “master code ninjas” start with their mental diarrhea – SQLite is good for learning, but they are not good for professional use:
- SQLite is file-based. It works great on a small single-server setup but fails horribly on large and distributed structures.
- Since the database file can only exist on one server, mirroring it across all servers becomes a challenge instead.
- Not good when it comes to performance.
- Has reliability and security issues.
So yes, PostgreSQL, MySQL, Redis, or MongoDB – At least pick one of these up.
LINKS & REFERENCES
- Python Flask
- SQLite
- Javascript Tagging Widget – Code Boxx
THE END
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!