0

I need to display an HTML file as a web page when a client makes a request using SocketServer or built in Python URL packages. My problem is that my displayIndex function currently displays the contents of the HTML file and not a rendered web page. Here's the function:

 def displayIndex(self):
        header = "Content-Type: text/html\r\n\r\n"
        f = open('index.html', 'r')
        dataToSend = header
        for line in f:
            dataToSend = dataToSend + line
        self.request.sendall(dataToSend)

And here are the contents of index.html, which are shown as code when calls are made to displayIndex:

<!DOCTYPE html>
<html>
<head>
        <title>Example Page</title>
        <meta http-equiv="Content-Type"
        content="text/html;charset=utf-8"/>
        <!-- check conformance at http://validator.w3.org/check -->
        <link rel="stylesheet" type="text/css" href="base.css">
</head>

<body>
        <div class="eg">
                <h1>An Example Page</h1>
                <ul>
                        <li>It works?
                        <li><a href="deep/index.html">A deeper page</a></li>
                </ul>
        </div>
</body>
</html> 
2
  • Error Traceback? What exactly is the problem? Commented Jan 19, 2014 at 8:08
  • @GamesBrainiac, I want html file to be displayed as a web page, but only contents of html file (with html tags) is displayed in the client side Commented Jan 19, 2014 at 8:15

2 Answers 2

1

I guess what you may be looking for is something like

import webbrowser
url = "file://" + somepath + "/" + "index.html"
webbrowser.open(url)

See webbrowser. This will send a command to display the file to your ordinary web browser (Firefox or so).

Sign up to request clarification or add additional context in comments.

Comments

0

Please refer SimpleHTTPServer module.

From the python docs, the following should work. It'll automatically look for the index.html file.

import SimpleHTTPServer
import SocketServer

PORT = 80

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.