我有这样的代码可以在Python3上运行简单的服务器。我知道我可以使用像这样的python -m http.server 8080
,但是我想了解它是如何工作的,并为提供文件扩展名设置限制。
我尝试使用path.join(dir, 'index.html')
,但看起来不起作用。
>> TypeError: join() argument must be str or bytes, not 'builtin_function_or_method'
<>
from http.server import BaseHTTPRequestHandler, HTTPServer
from os import path
hostName = "localhost"
hostPort = 8080
class RequestHandler(BaseHTTPRequestHandler):
dir = path.abspath(path.dirname(__file__))
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, 'index.html')
else:
content_path = path.join(dir, str(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()
https://stackoverflow.com/questions/51181876
复制相似问题