1

我正在尝试使用 Python 中的内置 HTTP 服务器打印一些简单的变量

class WebServer:
    def __init__(self):
        from BaseHTTPServer import HTTPServer
        import urlparse
        server = HTTPServer(('', 8080), self.do_GET)
        server.serve_forever()

    def do_GET(self):
        parsed_path = urlparse.urlparse(self.path)
        message_parts = [
                'CLIENT VALUES:',
                'client_address=%s (%s)' % (self.client_address, self.address_string()),
                'command=%s' % self.command,
                'path=%s' % self.path,
                'real path=%s' % parsed_path.path,
                'query=%s' % parsed_path.query,
                'request_version=%s' % self.request_version,
                '',
                'SERVER VALUES:',
                'server_version=%s' % self.server_version,
                'sys_version=%s' % self.sys_version,
                'protocol_version=%s' % self.protocol_version,
                '',
                'HEADERS RECEIVED:',
                ]
        for name, value in sorted(self.headers.items()):
            message_parts.append('%s=%s' % (name, value.rstrip()))
        message_parts.append('')
        message = '\r\n'.join(message_parts)
        self.send_response(200)
        self.end_headers()
        self.wfile.write(message)
        return

但我似乎得到了这个错误:

Exception happened during processing of request from ('10.0.1.3', 52251)
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 295, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
    self.RequestHandlerClass(request, client_address, self)
TypeError: do_GET() takes exactly 1 argument (4 given)
----------------------------------------

def do_GET(self): 似乎收到的不仅仅是 self,我错过了什么?

4

2 回答 2

2

BaseHTTPRequestHandler当预期a 时,您正在传递一个函数。换句话说,Python 正在尝试使用一种BaseHTTPRequestHandler __init__方法来实例化您的对象,但是您提供了一个接受不同数量参数的函数。

而不是传递一个普通的函数, sublcas BaseHTTPRequestHandler。@dm03514 在评论中链接的示例将帮助您入门。

于 2013-02-05T18:14:59.990 回答
2

WebServer从请求处理程序继承,如下所示:

class WebServer(BaseHTTPRequestHandler):

您可能必须为此更改导入。

然后将它作为参数传递给HTTPServer这样的:

server = HTTPServer(('', 8080), WebServer)
于 2013-02-05T18:16:09.377 回答