Simple Tags System With Python Flask (Free Download)

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!

ⓘ 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.

 

 

TABLE OF CONTENTS

Download & Notes Python Tags Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Create your own project folder, e.g. D:\tags, unzip the code inside this folder.
  • Open the terminal (or command line), navigate to your project folder cd D:\tags.
  • As usual, create a virtual environment if you don’t want to mess up your other projects.
    • virtualenv venv
    • Windows – venv\scripts\activate
    • Mac/Linux – venv/bin/activate
  • Get all the packages – pip install Flask
  • Create the database python s2_create.py
  • Launch! python s4_server.py and access http://localhost.

 

 

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 TAGS

All right, let us now get into the details of creating a simple tagging system with Python Flask and SQLite.

 

STEP 1) TAGS DATABASE TABLE

s1_tags.sql
-- (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.

 

 

STEP 2) CREATE THE DATABASE

s2_create.py
# (A) LOAD PACKAGES
import sqlite3, os
from sqlite3 import Error

# (B) DATABASE + SQL FILE
DBFILE = "tags.db"
SQLFILE = "s1_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 3) TAGS LIBRARY MODULE

s3_lib.py
# (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.

  1. Use the SQLite module. Doh.
  2. query() Helper function to run an SQL query.
  3. fetch() Helper function to run a SQL SELECT.
  4. get() Get all tags for the given content ID.
  5. delete() Delete all tags for the given content ID.
  6. 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 4) FLASK SERVER

s4_server.py
# (A) INIT
# (A1) LOAD MODULES
from flask import Flask, render_template, request, make_response
import s3_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("s5_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 5) HTML PAGE

templates/s5_tags.html
<div class="tagwrap">
  {% for t in tags %}
  <div class="tag">{{ t }}</div>
  {% endfor %}
</div>

Loop through the tags, and output them in HTML. The end.

 

 

USEFUL 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.

 

IT’S NOT A COMPLETE SYSTEM

Of course, this is only a barebones example, a starting point. The sorely missing pieces are probably:

  • No admin panel to manage the tags.
  • Fixed to one single piece of content.
  • Probably not a good idea to use SQLite for live systems.
  • No “search by tag” feature.

Everyone has a different starting point and requirement, so this is your “homework”.

 

 

SQLITE & FILE-BASED SESSIONS ARE NOT GOOD

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

 

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!

Leave a Comment

Your email address will not be published.