【发布时间】:2018-07-05 10:59:58
【问题描述】:
我有这样的代码用于在 Python 3 上运行简单服务器。我知道我可以使用类似 python -m http.server 8080 的东西,但是我想了解它是如何工作的并设置服务文件扩展名的限制。
我尝试使用path.join(DIR_PATH, self.path),但似乎不起作用。
>> FileNotFoundError: [WinError 2]: 'c:/test.html'
但是DIR_PATH = 'C:\script_path\src\'
但是它适用于/ 请求的路径和服务器打开index.html。
因此,path.join(DIR_PATH, 'index.html') 是有效的。
from http.server import BaseHTTPRequestHandler, HTTPServer
from os import path
DIR_PATH = path.abspath(path.dirname(__file__))
hostName = "localhost"
hostPort = 8080
class RequestHandler(BaseHTTPRequestHandler):
content_type = 'text/html'
def _set_headers(self):
self.send_response(200)
self.send_header('Content-Type', self.content_type)
self.send_header('Content-Length', path.getsize(self.getPath()))
self.end_headers()
def do_GET(self):
self._set_headers()
self.wfile.write(self.getContent(self.getPath()))
def getPath(self):
if self.path == '/':
content_path = path.join(DIR_PATH, 'index.html')
else:
content_path = path.join(DIR_PATH, self.path)
return content_path
def getContent(self, content_path):
with open(content_path, mode='r', encoding='utf-8') as f:
content = f.read()
return bytes(content, 'utf-8')
myServer = HTTPServer((hostName, hostPort), RequestHandler)
myServer.serve_forever()
【问题讨论】:
标签: python-3.x httpserver simplehttpserver