Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 files are in the same directory btw.

simplehttpwebsite.py

#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
server = SocketServer.TCPServer(('0.0.0.0', 8080), Handler)

server.serve_forever()

simplehttpwebsite_content.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="simplehttpwebsite_style.css">
  </head>

  <body>
    This is my first web page
  </body>
</html>

simplehttpwebsite_style.css

body{background-color:blue;}
like image 339
Bentley4 Avatar asked May 15 '12 19:05

Bentley4


2 Answers

You can extend SimpleHTTPServer.SimpleHTTPRequestHandler and override the do_GET method to replace self.path with simplehttpwebpage_content.html if / is requested.

#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer

class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.path = '/simplehttpwebpage_content.html'
        return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

Handler = MyRequestHandler
server = SocketServer.TCPServer(('0.0.0.0', 8080), Handler)

server.serve_forever()

Since SimpleHTTPServer.SimpleHTTPRequestHandler extends BaseHTTPServer.BaseHTTPRequestHandler, you can read their documentations to figure what methods and instance variables are available and how you can manipulate them.

You can find the path variable mentioned in the documentation of BaseHTTPServer.BaseHTTPRequestHandler. You can find the do_GET() method mentioned in the documentation of SimpleHTTPServer.SimpleHTTPRequestHandler.

Here is some output from my shell to show what happens when I run this program and then I try to access http://localhost:8080/

susam@swift:~/so$ ls
simplehttpwebpage_content.html  simplehttpwebpage.py  simplehttpwebsite_style.css
susam@swift:~/so$ python simplehttpwebpage.py
swift - - [19/Apr/2012 09:10:23] "GET / HTTP/1.1" 200 -
swift - - [19/Apr/2012 09:10:26] "GET /simplehttpwebsite_style.css HTTP/1.1" 200 -
like image 78
Susam Pal Avatar answered Oct 30 '22 18:10

Susam Pal


you should call your file index.html, that's the page that gets served automatically instead of listing the directory.

the other possibility would be to override the handlers list_directory(self, path) method.

like image 27
mata Avatar answered Oct 30 '22 19:10

mata