سؤال

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> 
هل كانت مفيدة؟

المحلول

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).

نصائح أخرى

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()
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top