[英]Simple HTTP server in Python. How to GET files?
我有用于在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
是一个内置函数。 您正在尝试将该函数连接到字符串'index.html'
,因此出现错误。
您可能感到困惑的原因是您尝试使用字符串隐藏dir
,如下所示:
dir = path.abspath(path.dirname(__file__))
但是,当您将其放在class
定义中时,它不会创建隐藏内置函数的全局变量,而是会创建类属性。 要从该类的方法中访问类属性,您必须执行与普通实例属性相同的操作:
content_path = path.join(self.dir, 'index.html')
类属性和实例属性之间的唯一区别是:
dir
属性,而不是每个实例都有自己的副本。 RequestHandler.dir
或type(self).dir
而不是self.dir
。 为避免这种混淆,最好避免重用任何内置函数的名称。 尽管这样做是合法的 ,但它经常会导致与此类似的错误,并使调试这些错误变得更加困难。
同样,由于dir
是整个程序中的常量,就像hostName
和hostPort
一样,并且与RequestHandler
类型并没有紧密联系,也许您只是想要一个全局常量,例如hostName
,而不是类属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.