2
\$\begingroup\$

The following code was written to create custom directory listings for the Abyss Web Server. It attempts to provide an improved example of the included documentation for doing so in Python. However, some modules such as cgi and cgitb are deprecated and should be replaced to modernize this example code even more.

Could some guidance be provided on how to write the following using state-of-the-art techniques limited to using the standard library?

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""Directory Listing Program for Abyss Web Server.

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

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

For more information, please refer to <http://unlicense.org/>"""

import cgi
import cgitb
import csv
import datetime
import html
import io
import math

# Public Names
__all__ = (
    'KB',
    'MIME_TYPE',
    'PREFIX',
    'main',
    'write_header',
    'write_body_line',
    'bytes_to_str',
    'utc_to_local',
    'write_footer'
)

# Module Documentation
__version__ = 1, 0, 0
__date__ = datetime.date(2022, 6, 10)
__author__ = 'Stephen Paul Chappell'
__credits__ = 'Aprelium, for providing the inspiration for this program.'

# Symbolic Constants
KB = 1 << 10
MIME_TYPE = 'text/html; charset=utf-8'
PREFIX = '', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'


def main():
    """Generate a custom directory listing for Abyss Web Server."""
    cgitb.enable()
    posted_data = cgi.FieldStorage()
    print(f'Content-Type: {MIME_TYPE}\n')
    write_header(posted_data['path'].value)
    with io.StringIO(posted_data['files'].value, '') as files:
        for row in csv.reader(files, csv.excel_tab):
            write_body_line(*row)
    write_footer()


def write_header(path):
    """Create a mostly static header for the directory listing to follow."""
    print(f'''\
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Index of {path}</title>
        <style>
            table {{
                border-style: hidden;
                font-family: monospace;
                font-size: smaller;
            }}
            thead {{
                background-color: white;
                position: sticky;
                top: 0;
            }}
            .name, .size, .date {{
                padding-right: 1em;
            }}
            .size {{
                text-align: right;
            }}
            .size, .date {{
                white-space: nowrap;
            }}
            .special {{
                font-style: italic;
                font-weight: bold;
            }}
        </style>
    </head>
    <body>
        <header>
            <h2>Index of {path}</h2>
        </header>
        <hr>
        <main>
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Size</th>
                        <th>Date</th>
                        <th>MIME Type</th>
                    </tr>
                </thead>
                <tbody>''')


def write_body_line(name, url, size, date, mime_type):
    """Create one table row for the current directory/file being processed."""
    print(f'''\
                    <tr>
                        <td class="name">
                            <a href="{url}">{html.escape(name)}</a>
                        </td>
                        <td class="size">{bytes_to_str(size)}</td>
                        <td class="date">{utc_to_local(date)}</td>
                        <td>{mime_type if mime_type else "Directory"}</td>
                    </tr>''')


def bytes_to_str(size):
    """Convert an item's size in bytes to an easily readable representation."""
    size = int(size)
    if size:
        selector = round(math.log(size, KB) - 0.4)
        if selector:
            return f'{size / KB ** selector:.2f} {PREFIX[selector]}B'
        return f'{size:d} {PREFIX[selector]}B'
    return '-'


def utc_to_local(date):
    """Convert the UTC time from the server to be displayed in local time."""
    naive = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
    utc = naive.replace(tzinfo=datetime.timezone.utc)
    local = utc.astimezone()
    return local.strftime('%b %d, %Y %H:%M:%S')


def write_footer():
    """Create the document's footer with the current year filled in."""
    print(f'''\
                </tbody>
            </table>
        </main>
        <hr>
        <footer>
            Powered by
            <span class="special">Abyss Web Server</span>
            X1
            <br>
            Copyright &copy;
            <a href="https://www.aprelium.com">Aprelium</a>
            - 2001-{datetime.date.today().year}
        </footer>
    </body>
</html>''')


if __name__ == '__main__':
    main()
\$\endgroup\$
1
  • 2
    \$\begingroup\$ It's standard practice to include non-built-ins. Ruling out e.g. Jinja out of some nondescript aversion to third-party libraries produces worse code. \$\endgroup\$
    – Reinderien
    Jun 14, 2022 at 16:13

1 Answer 1

2
\$\begingroup\$

You care about state of the art: that's good! But CGI and state of the art do not go in the same sentence.

You're writing for integration to a specific server, Abyss, whose Python support explicitly requires CGI. You may or may not have already read this in the documentation for Python's CGI module:

Deprecated since version 3.11: The cgi module is deprecated (see PEP 594 for details and alternatives).

So it's very important that you read and understand PEP 594, including its claim that CGI support is poorly-designed and nearly impossible to fix; and offers replacements.

If I had to venture a guess as to what actual state-of-the-art scripting support would look like, and I have no idea whether Abyss intends on supporting this: it's the web server acting as a frontend, proxying to a Python WSGI host, similar to what Nginx can do. (Operating on the little information I have about Abyss, I would overwhelmingly recommend Nginx over it).

\$\endgroup\$
1
  • \$\begingroup\$ The server also explicitly supports being used as a reverse proxy and could be used as a frontend for whatever is running the Python application. Further discussion of your answer would need to be conducted in chat. \$\endgroup\$ Jul 20, 2022 at 15:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.