【问题标题】:python 3.6 BaseHTTPRequestHandlerpython 3.6 BaseHTTPRequestHandler
【发布时间】:2018-03-15 08:59:53
【问题描述】:

我正在尝试做一个服务器程序员。代码如下所示:

class ALNHTTPRequestHandler(BaseHTTPRequestHandler):
prefix = r'/Users/huxx/PycharmProjects/ServerDemo'
# handle GET command
def do_GET(self):
    rootdir = ALNHTTPRequestHandler.prefix  # file location
    try:
        if self.path.endswith('.html'):
            finalPath = rootdir + self.path
            with open(finalPath, 'rb') as f:
                print('open successed')
            # send code 200 response
                self.send_response(200)
            # send header first
                self.send_header('Content-type', 'text-html')
                self.end_headers()
            # send file content to client
                a = f.read()
                self.wfile.write(a)
                # self.wfile.write(f.read())
                return

    except IOError:
        print('well not found')
        self.send_error(404, 'file not foundbbbb')
def run():
    print('http server is starting...')
    server_address = ('127.0.0.1', 8011)
    httpd = HTTPServer(server_address,ALNHTTPRequestHandler)
    print('http server is running...')
    httpd.serve_forever()


if __name__ == '__main__':
    run()

问题是,如果我使用 self.wfile.write(f.read()) 而不是 self.wfile.write(a),则根本没有响应。这是为什么呢?

【问题讨论】:

    标签: python python-3.x basehttprequesthandler


    【解决方案1】:

    这与read() 方法的工作方式有关。首先,让我们关注这一行:

    self.wfile.write(f.read())
    

    read() 基本上会读取您的类文件对象 (f),并且在完成此方法的调用后,指针会停留在内存地址的末尾。您可以将其想象为文件的“一次读取”操作。之后,write() 调用开始并且没有任何内容可写(因为指针在末尾),因此似乎没有响应。现在让我们看看替代方案:

    a = f.read()
    self.wfile.write(a)
    

    在这种情况下,您将数据从f.read() 读取到内存,并且它作为字符串保留在变量a 中。您以后可以根据需要多次读取此变量(除非您将其删除),这正是后续 write() 调用所做的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 2020-07-08
      • 2019-12-19
      相关资源
      最近更新 更多