How does list_directory() of http.server work?

The list_directory of http.server generates a directory listing for the given directory path. So, how does it translate the local file names to appropriate hyperlinks in the http server directory listing?

For example, if there is a file in a directory, like /home/user/dir/file.txt then how does, the list_directory() generate the appropriate hyperlink like http://localhost:8080/dir/file.txt and how does it sends the file for download, when the file is requested via the http server webpage?

It seems that you are curious about the implementation of list_directory.

You have the source code installed with your version of python you can read the code to see how it works.

If you are not sure where the code is then you can do this:

>>> import http.server
>>> http.server
<module 'http.server' from '/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/http/server.py'>

You can see the file name of server.py is shown.

Yes, I have looked at the source code. The thing I don’t understand is how the wfile is sending back the data and how the data is read using rfile? Can you please explain me, how it works?

There are comments in the source telling you what rfile and wfile are.

    - rfile is a file object open for reading positioned at the
    start of the optional input data part;

    - wfile is a file object open for writing.

rfile and wfile are the read and write sides of the TCP connection from the browser.

To understand list_directory you need to read translate_path.
translate_path is returning files relative to the directory you start the server in unless you pass in directory as documented:

 class http.server.SimpleHTTPRequestHandler(request, client_address, server, directory=None)

    This class serves files from the directory directory and below, or the current directory if directory is not provided, directly mapping the directory structure to HTTP requests.

If you follow the code from do_GET into send_head you will see where the data to be returned is determined. Then self.copyfile is used to copy the data to the browser via self.wfile.

1 Like

Thankyou! I was really looking for the translate_path method. Also, if rfile and wfile are browser side implementation, how are they being accessed in python?

These are the read and write FILE objects that are connected to the TCP connection from the browser.

Browser <-> TCP connection <-> server.http

Does that mean, they are defined by the python language internally?

You need to learn about network programming i am guessing from your questions.

Maybe this will help Socket Programming HOWTO — Python 3.11.1 documentation
Also maybe read the python docs for the socket module.

I will take a look at them. Thanks for helping :slight_smile:

I have a question, I want to sent bulk mssages to insta followers but instagram is not allowing me. I doing this using python instabot scrip.