HTTP server

placid Bulkan at
Wed Jun 28 03:07:11 CEST 2006

Hi all,

Im having trouble with the following code for handling GET requests
from a client to my HTTP server. What i want to do is restrict access
only to a folder and contents(files) within this folder. But when
trying to
open files (eg text files) i get file not found error from send_head()
method of SimpleHTTPServer. The reason behind this is when opening the
file the path to the file is only C:\file.txt when it should be
C:\folder\file.txt. And when i remove the code that checks if path
contains "txt" it works (i can access files without errors).

Any help will be greatly appreciated!

    def list_directory(self, path):
        """Helper to produce a directory listing (absent index.html).

        Return value is either a file object, or None (indicating an
        error).  In either case, the headers are sent, making the
        interface the same as for send_head().

        f = StringIO()

        p = self.translate_path(self.path)
        if p.find("txt") == -1:
            f.write("<title> Access Denied</title>" )
            f.write("<h2> Access Denied</h2>" )
                list = os.listdir(path)
            except os.error:
                self.send_error(404, "No permission to list directory")
                return None

            list.sort(key=lambda a: a.lower())

            displaypath = cgi.escape(urllib.unquote(self.path))
            f.write("<title>Directory listing for %s</title>\n"
            f.write("<h2>Directory listing for %s</h2>\n" %
            for name in list:
                fullname = os.path.join(path, name)
                displayname = linkname = name
                # Append / for directories or @ for symbolic links
                if os.path.isdir(fullname):
                    displayname = name + "/"
                    linkname = name + "/"
                if os.path.islink(fullname):
                    displayname = name + "@"
                    # Note: a link to a directory displays with @ and
links with /
                f.write('<li><a href="%s">%s</a>\n'  %
(urllib.quote(linkname), \


        length = f.tell()
        self.send_header("Content-type", "text/html")
        self.send_header("Content-Length", str(length))
        return f

More information about the Python-list mailing list