Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to display file size in a directory served using http.server in python?

I've served a directory using

python -m http.server

It works well, but it only shows file names. Is it possible to show created/modified dates and file size, like you see in ftp servers?

I looked through the documentation for the module but couldn't find anything related to it.

Thanks!

like image 642
mankand007 Avatar asked Mar 02 '26 00:03

mankand007


1 Answers

http.server is meant for dead-simple use cases, and to serve as sample code.1 That's why the docs link right to the source.

That means that, by design, it doesn't have a lot of configuration settings; instead, you configure it by reading the source and choosing what methods you want to override, then building a subclass that does that.

In this case, what you want to override is list_directory. You can see how the base-class version works, and write your own version that does other stuff—either use scandir instead of listdir, or just call stat on each file, and then work out how you want to cram the results into the custom-built HTML.

Since there's little point in doing this except as a learning exercise, I won't give you complete code, but here's a skeleton:

class StattyServer(http.server.HTTPServer):
    def list_directory(self, path):
        try:
            dirents = os.scandir(path)
        except OSError:
            # blah blah blah
        # etc. up to the end of the header-creating bit
        for dirent in dirents:
            fullname = dirent.path
            displayname = linkname = dirent.name
            st = dirent.stat()
            # pull stuff out of st
            # build a table row to append to r

1. Although really, it's sample code for an obsolete and clunky way of building servers, so maybe that should be "to serve as sample code to understand legacy code that you probably won't ever need to look at but just in case…".

like image 57
abarnert Avatar answered Mar 04 '26 15:03

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!