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

标签 python networking webpage

如何在访问 localhost:8080 时只显示 simplehttpwebsite_content.html?这样我就看不到我的文件树,只能看到网页。顺便说一下,所有这些文件都在同一个目录中。

简单的httpwebsite.py

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

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

server.serve_forever()

简单的httpwebsite_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>

简单的httpwebsite_style.css

body{background-color:blue;}

最佳答案

您可以扩展 SimpleHTTPServer.SimpleHTTPRequestHandler 并覆盖 do_GET 方法以将 self.path 替换为 simplehttpwebpage_content.html 如果请求 /

#!/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()

SimpleHTTPServer.SimpleHTTPRequestHandler延伸BaseHTTPServer.BaseHTTPRequestHandler ,您可以阅读他们的文档,了解哪些方法和实例变量可用以及如何操作它们。

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

这是我的 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 -

关于python - 一个使用 SimpleHTTPServer 和 SocketServer 的 python 简单网站,如何只显示 html 文件而不显示整个目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10607621/

相关文章:

python - 在不知道键的情况下访问 python dict() 的值

sockets - 应用程序应何时设置定义 SYN 重传次数的 TCP 选项?

python - 用 Mechanize 打开网页后,如何继续提交

javascript - 页眉或页脚中的 Google 分析?

Python:创建一个根据条件变化的递增变量

python - 哪个Python IDE在运行后提供Python控制台(如Spyder)?

python - 如何替换数据框中行中的字符?

perl - 如何在我的 Perl 模块测试中检查网络可用性?

scala - 让两个本地实例与 Akka 参与者通信所需的最少代码是多少?

html - 单击时在 div 中加载链接的页面内容