문제

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