gif gif

The interesting corner

gif gif

Generate HTML page with Python

This is a script that I made to quickly generate a HTML page for this website using a specific template. It uses the Dominate library to create the HTML page. Download it here: Download button

UPDATE 23-07-2024: Added style links and script references for prism.js

UPDATE 23-06-2025: Added corner table integration and setting a random image as background for the header>


      
import glob
import dominate
from dominate.tags import *
import mysql.connector
from cryptography.fernet import Fernet
from datetime import datetime
import os
import random

IMAGE_DIRECTORY = "/image-directory"
corners = ["Audio equipment", "Blog", "Computers", "Electronics", "Servers", "Hardware", "Games", "Programming", "Cars"]

# get a random background image from the tiles-backgrounds directory
bg_imgs = []
for (dirpath, dirnames, filenames) in os.walk(IMAGE_DIRECTORY + '/img/tiles-backgrounds/'):
    for filename in filenames:
        img_path = os.path.join(dirpath, filename).replace("/public-path", "")
        bg_imgs.append(img_path)
        
random_bg_img = random.choice(bg_imgs)
print("Random background image is: " + random_bg_img)

with open("key", "rb") as filekey:
    key = filekey.read()

fernet = Fernet(key)

with open("db", "rb") as dbpass:
    encrypted = dbpass.read()

decrypted = fernet.decrypt(encrypted).decode()

print("Logging in to db...")
connection = mysql.connector.connect(host='ip address',
                                        database='db',
                                        user='username',
                                        password=decrypted)
if connection.is_connected():
    db_Info = connection.server_info
    print(db_Info)

cursor = connection.cursor(dictionary=True)

cur_date = datetime.today().strftime('%Y-%m-%d')

title_text = str(input("Enter title of page: ").strip())

pagename = input("Enter the name of the file and the page identifier (for example autoprefixer-grunt): ").strip()
corner = input("Enter the corner of the page (Blog, Games, etc): ").strip()

url = "/" + corner.lower() + "/" + pagename

query = "INSERT INTO routes (name, url, date) VALUES (\"{}\", \"{}\", \'{}\')".format(title_text, url, cur_date)
cursor.execute(query)

query = "SELECT ID from routes ORDER BY ID DESC LIMIT 1"
cursor.execute(query)

corner_id = 0
for i in range(len(corners)):
        if corners[i] == corner:
            corner_id = i
            break

new_id = cursor.fetchall()[0]['ID']
query = "INSERT INTO routes_corners (route_id, corner_id) values (" + str(new_id) + ", " + str(corner_id + 1) + ");"

cursor.execute(query)

cursor.execute("SELECT * FROM routes")
for row in cursor.fetchall():
    print(row)

print()

blogpost = input("Is this a blog post? (y/n) : ") == 'y'
 
if blogpost:
    cursor.execute("SELECT ID from routes ORDER BY ID DESC LIMIT 1")
    for row in cursor.fetchall():
        route_id = row['ID']
        print("Route ID is: " + str(route_id))
        post_type = input("Enter the type of post (blog post, image gallery, story, website update): ").strip()
        cursor.execute("INSERT INTO blogposts (post_type, route_id) VALUES ('{}', {})".format(post_type, route_id))
        cursor.execute("SELECT * FROM blogposts")
        for row in cursor.fetchall():
            print(row)
        break;

print()

navigations = input("Enter navigation links comma separated by names (link1,name1 link2,name2 ...): ").strip()
navlist = navigations.split(' ')

subimgleft = input('Enter the image location of the left sub img: ').strip()
subimgright = input('Enter the image location of the right sub img: (enter for the same as left) : ').strip()
if (len(subimgright) <= 0):
    subimgright = subimgleft

add_imgs = input("Do you want to add an image gallery? (y/n) : ") == 'y'
if (add_imgs):
    img_folder = input("Enter the folder that contains the images for the gallery : ").strip()
    imgs = []
    imgs = glob.glob(IMAGE_DIRECTORY + img_folder  + "/*.jpg")
    for i in (glob.glob(IMAGE_DIRECTORY + img_folder + "/*.JPG")):
        imgs.append(i)
    for i in (glob.glob(IMAGE_DIRECTORY + img_folder + "/*.png")):
        imgs.append(i)
    print("imgs are: ")
    for i in range(len(imgs)):
        ind = len(imgs[i])-len(IMAGE_DIRECTORY)
        imgs[i] = imgs[i][-ind:]
    print(imgs)
    print()


create_hardware = input("Do you want to create a hardware page? (y/n) : ") == 'y'
if create_hardware:
    fields = input("Enter the fields for this entry separated by commas : ").strip().split(',')
    datasheets = input("Enter semicolon separated datasheets (link1,name1;link2,name2 ...), or Enter for none : ").strip().split(';')
    print(datasheets)

doc = dominate.document(title=title_text)

with doc.head:
    link(rel='preconnect',href='https://fonts.googleapis.com')
    link(rel='preconnect',href='https://fonts.gstatic.com')
    link(rel='stylesheet',href='https://fonts.googleapis.com/css2?family=IBM+Plex+Mono&display=swap')
    link(rel='stylesheet',href='/css/stylesheet.css')
    link(rel='stylesheet',href='/css/animations.css')
    link(rel='stylesheet',href='/css/stylesheet-hardware.css')
    # link(rel='stylesheet',href='/js/prism/prism.full.css')
    link(rel='stylesheet',href='/js/prism/themes/prism-laserwave.css')
    meta(name='viewport',content='width=device-width, initial-scale=1.0')

with doc:
    with div(cls='sidenav'):
        with table(cls='navigation'):
            tr(th('Navigation'))
            print(len(navlist))
            if (len(navlist) > 1):
                for i in navlist:
                    tr(td(a(i.split(',')[1],href=i.split(',')[0])))
            else:
                tr(td(a('Home',href='/')))
    with div(cls='bg-container', style='background-image: url(' + random_bg_img + ');'):
        with div(cls='titleheaderdiv'):
            with div():
                img(src='/img/ice-cream-parrot.gif',alt='gif',id='imgleft')
                img(src='/img/pizzaparrot.gif',alt='gif',id='imgright')
                h1("The interesting corner",id='titletext')
        with div(cls='titleheaderdiv'):
            with div():
                img(src=subimgleft, alt='gif', id='subimgleft')
                img(src=subimgright, alt='gif', id='subimgright')
                h1(title_text,id='subtitle')     

    with div(cls='textlist'):
        if create_hardware or add_imgs:

            with div(cls='hardware-information'):
                if (add_imgs):
                    with div(cls='hardware_row'):
                        for imgval in imgs:
                            with div(cls='hardware_column'):
                                img(src=imgval,alt='',onclick='addImage(this)')
                    with div(cls='hardware_container'):
                        span("x",onclick="this.parentElement.style.display='none'",cls='hardware_closebtn')      
                        img(id="hardware_expandedimg")
                        div(id="hardware_imgtext")
                if (create_hardware):
                    with table():
                        for f in fields:
                            with tr():
                                td(f)
                                td(input("Enter " + f + " : "))
                        if (len(datasheets[0]) > 1):
                            with tr():
                                td("Library Entries")
                                with td():
                                    with ul(id='datasheets'):
                                        for d in datasheets:
                                            li(a(d.split(',')[1], href=d.split(',')[0]))
                            
    script(src='/js/add-navbar.js')
    script(src='/js/animations.js')
    script(src='/js/prism/prism.full.js')
    if add_imgs:       
        script(src='/js/hardware-image.js')


print(doc.render())

try:
    os.makedirs("/corner-location" + corner.lower())
except FileExistsError:
    print("Directory already exists")
    pass

savefile ="/save-file-location" + url + ".ejs"
print("Saving file to " + savefile)
with open(savefile, 'w') as f:
    f.write(doc.render())
    print("Successfully written file!")

connection.commit()

connection.close()