一个简单的网站用python使用SimpleHTTPServer和SocketServer,如何只显示html文件而不是整个目录?

Ben*_*ey4 10 python networking webpage

我如何只simplehttpwebsite_content.html在访问时显示localhost:8080?所以我看不到我的filetree,只看到网页.所有这些文件都在同一个目录中.

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()
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

simplehttpwebsite_style.css

body{background-color:blue;}
Run Code Online (Sandbox Code Playgroud)

Sus*_*Pal 23

您可以扩展SimpleHTTPServer.SimpleHTTPRequestHandler和覆盖do_GET要替换self.pathsimplehttpwebpage_content.htmlif 的方法/.

#!/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()
Run Code Online (Sandbox Code Playgroud)

SimpleHTTPServer.SimpleHTTPRequestHandler扩展以来BaseHTTPServer.BaseHTTPRequestHandler,您可以阅读其文档以了解可用的方法和实例变量以及如何操作它们.

您可以找到path文档中提到的变量BaseHTTPServer.BaseHTTPRequestHandler.您可以找到do_GET()文档中提到的方法SimpleHTTPServer.SimpleHTTPRequestHandler.

这是我的shell的一些输出,以显示当我运行此程序然后我尝试访问时会发生什么 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 -
Run Code Online (Sandbox Code Playgroud)


mat*_*ata 12

你应该调用你的文件index.html,这是自动提供的页面,而不是列出目录.

另一种可能性是覆盖处理程序list_directory(self, path)方法.