HTTP server

placid Bulkan at gmail.com
Tue Jun 27 01:09:57 EDT 2006


Simon Forman wrote:
> ...
> >
>
> Awesome!  Glad to hear it.
>
> ...
> >
> > Thanks for the help. I got it to work now.
> >
>
> You're welcome.  I'm glad I could help you.  :-D
>

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 within this folder. But when trying to
open files (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!

<code>
    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>httpserver.py: Access Denied</title>" )
            f.write("<h2>httpserver.py: Access Denied</h2>" )
        else:
            try:
                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" %
displaypath)
            f.write("<h2>Directory listing for %s</h2>\n" %
displaypath)
            f.write("<hr>\n<ul>\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),
cgi.escape(displayname)))
            f.write("</ul>\n<hr>\n")

        length = f.tell()
        f.seek(0)
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.send_header("Content-Length", str(length))
        self.end_headers()
        return f
</code>




More information about the Python-list mailing list