【发布时间】:2018-07-04 23:56:52
【问题描述】:
我有这样的代码可以在 Python 3 上运行简单的服务器。我知道我可以使用类似 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()
【问题讨论】:
-
永远不要覆盖内置名称(在您的示例中为
dir)。使用对读者更有帮助的东西 (BASE_DIRECTORY) 或类似的东西。 -
这是一个简单的范围界定问题。在 python 中,您无法访问其函数内的类的范围。
标签: python python-3.x webserver httpserver simplehttpserver