A simple website with python using SimpleHTTPServer and SocketServer, how to only display the html file and not the whole directory?

前端 未结 3 1615
梦谈多话
梦谈多话 2020-12-28 22:46

How do I only display simplehttpwebsite_content.html when I visit localhost:8080? So that I can\'t see my filetree, only the webpage. All these fil

3条回答
  •  梦谈多话
    2020-12-28 23:20

    Building on Susam Pal's answer, here is my implementation which allows the port to be set (just like when you run python -m SimpleHTTPServer 8080) and also serves up html pages when the file exists on the file server, without the .html extension.

    #!/usr/bin/env python
    import SimpleHTTPServer
    import SocketServer
    import os.path
    import sys
    
    class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
        def do_GET(self):            
            possible_name = self.path.strip("/")+'.html'
            if self.path == '/':
                # default routing, instead of "index.html"
                self.path = '/simplehttpwebpage_content.html'
            elif os.path.isfile(possible_name):
                # extensionless page serving
                self.path = possible_name
    
            return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
    
    Handler = MyRequestHandler
    
    port = 8000
    if len(sys.argv) > 1:
        try:
            p = int(sys.argv[1])
            port = p
        except ValueError:
            print "port value provided must be an integer"
    
    print "serving on port {0}".format(port)
    server = SocketServer.TCPServer(('0.0.0.0', port), Handler)
    server.serve_forever()
    

提交回复
热议问题