如何在访问 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/