August 14, 2021

Hard work pays off.

Though the CSS styling for this page is far from complete and needs a lot of work, the idea is fulfilled:

Basically, I created an entire art gallery page that creates itself.

How it works:

If you like Python 3, and source code, well, this is for you, since this is how I did it so you can do it on your site as well:

import os
from pathlib import Path
import pprint
import itertools

def main():
    with open('/var/www/musimatic/pythonprojectwebsites/ArtGallery/artgallery.html', 'w') as f:
        f.write('<html>')
        f.write('<head>')
        f.write('<title>Art Gallery</title>')
        f.write('<meta charset="utf-8"/>')
        f.write('<link rel="stylesheet" href="css/artgallery.css" type="text/css"/>')
        f.write('</head>')
        f.write('<body>')
        art_gallery_path = '/var/www/musimatic/images/ArtGallery'
        os.chdir(art_gallery_path)
        picture_directories = list(filter(os.path.isdir, os.listdir(art_gallery_path)))
        for directory in picture_directories:
            picture_directory_anchor = str('<a href="#' + str(directory) + '">' + str(directory) + '</a>')
            f.write(picture_directory_anchor)
            f.write('<br />')
        for directory in picture_directories:
            picture_directory_header = str('<h1 id="' + str(directory) + '">' + str(directory) + '</h1>')
            f.write(picture_directory_header)
            f.write('<br />')
            # SO Post on Globs:
            # https://stackoverflow.com/questions/4568580/python-glob-multiple-filetypes
            picture_paths_jpg = (x.resolve() for x in Path(directory).glob("*.jpg"))
            picture_paths_png = (x.resolve() for x in Path(directory).glob("*.png"))
            picture_paths_gif = (x.resolve() for x in Path(directory).glob("*.gif"))
            picture_paths = itertools.chain(picture_paths_jpg, picture_paths_png, picture_paths_gif)
            # SO Post on string replacement:
            # https://stackoverflow.com/questions/9452108/how-to-use-string-replace-in-python-3-x
            picture_paths_strings = [str(p).replace('/var/www/musimatic/', 'https://musimatic.xyz/') for p in picture_paths]
            pprint.pprint(picture_paths_strings)
            for picture_path in picture_paths_strings:
                picture_img_tag = str('<a target="_blank" href="' + str(picture_path) + '"><img src="' + str(picture_path) + '"/></a>')
                f.write(picture_img_tag)
        f.write('</body>')
        f.write('</html>')


if __name__ == '__main__':
    main()

~ Sam