Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active November 8, 2023 11:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/813db1d55d46e698a9317c94a0acdcc8 to your computer and use it in GitHub Desktop.
Save code-boxx/813db1d55d46e698a9317c94a0acdcc8 to your computer and use it in GitHub Desktop.
Simple Python Tags System

PYTHON TAGS SYSTEM

https://code-boxx.com/simple-tags-system-python-flask/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Create a templates folder, move S4_tags.html inside.
    • Create a static folder, move S4_tags.css inside.
    • Save the sample images below into static.
    • 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 tags database - python S1B_create.py
    • Run python S3_server.py to start the server.
  2. Access http://localhost in your browser.

IMAGES

lasagna

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) TAGS TABLE
CREATE TABLE `tags` (
`content_id` INTEGER NOT NULL,
`tag_name` TEXT NOT NULL,
PRIMARY KEY("content_id", "tag_name")
);
-- (B) DUMMY TAGS
INSERT INTO `tags`
(`content_id`, `tag_name`)
VALUES
(999, "Food"),
(999, "Italian"),
(999, "MAMAMIA"),
(999, "Meat");
# (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!")
# (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
# (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)
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
.product {
width: 400px;
padding: 20px;
border: 1px solid #ffd3d3;
background: #ffe7ea;
}
.pImg { width: 100%; }
.pName {
font-size: 20px;
font-weight: 700;
}
.pDesc {
color: #333;
}
.pTags {
display: flex;
flex-wrap: wrap;
margin-top: 10px;
}
.pTags .tag {
padding: 5px 20px;
margin-right: 5px;
border-radius: 20px;
font-size: 12px;
color: #fff;
background: #a93737;
}
<!DOCTYPE html>
<html>
<head>
<title>Demo Tags Page</title>
<meta charset="utf-8">
<link rel="stylesheet" href="static/S4_tags.css">
</head>
<body>
<div class="product">
<img class="pImg" src="static/lasagna.png">
<div class="pName">B-LASAGNA</div>
<div class="pDesc">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
<div class="pTags">
{% for t in tags %}
<div class="tag">{{ t }}</div>
{% endfor %}
</div>
</div>
</body>
</html>
md templates
md static
move S4_tags.html templates
move S4_tags.css static
curl https://user-images.githubusercontent.com/11156244/281386394-fdc55caa-4a9f-4815-809a-41a605081b06.png --ssl-no-revoke --output static/lasagna.png
virtualenv venv
call venv\Scripts\activate
pip install flask
python S1B_create.py
python S3_server.py
mkdir -m 777 templates
mkdir -m 777 static
mv ./S4_tags.html ./templates
mv ./S4_tags.css ./static
curl https://user-images.githubusercontent.com/11156244/281386394-fdc55caa-4a9f-4815-809a-41a605081b06.png --ssl-no-revoke --output ./static/lasagna.png
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