首页 > 解决方案 > 当阅读发生在 urllib

问题描述

考虑以下代码:

r = urllib.request.urlopen("https://example.com")
print(r.read())  # Does reading occurs at this point?

urlopen()我的问题是在被调用或被调用时何时发生读取read()

标签: pythonpython-3.xurllib

解决方案


在再次阅读文档并进行一些测试之后,我可以说两者都可以进行阅读。

urlopen是一个阻塞调用,实际上是在等待标题部分的结束。此时, code 和 headers 属性可用。

但是如果服务器很慢,urlopen可能在收到所有数据部分之前就返回了。在这种情况下,read(n)如果收到少于 n 个字节,则可能会阻塞,并且read()会阻塞直到收到所有响应。

代码证明:

服务器:

class ReqHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        print("GOT", self.command)
        print("Headers", self.headers)
        self.wfile.write(b"HTTP/1.1 200 OK\r\n")
        time.sleep(2)
        self.wfile.write(b"Server: BaseHTTP/0.6 Python/3.6.2\r\n\
Date: Mon, 11 Jun 2018 15:47:00 GMT\r\n\r\n")
        time.sleep(2)
        self.wfile.write("""<html>
<header><title>Test page</title></html>
<body><h1>Test</h1>
<p>This is a simple test...</p>""".encode())
        time.sleep(5)
        self.wfile.write("""<p>and here is the end of the page</p>
</body></html>""".encode())

server = http.server.HTTPServer(('localhost', 8080), ReqHandler)
server.handle_request()

客户:

def ask():
    print(time.asctime())
    r = urllib.request.urlopen("http://localhost:8080/test_page")
    print(time.asctime())
    print(r.read(10))
    print(time.asctime())
    print(r.read())
    print(time.asctime())

ask()

这是客户端的示例:

Mon Jun 11 18:13:12 2018
Mon Jun 11 18:13:15 2018
b'<html>\n<he'
Mon Jun 11 18:13:17 2018
b'ader><title>Test page</title></html>\n<body><h1>Test</h1>\n<p>Ceci est un simple test</p><p>mais avec des charact\xe8res accentu\xe9s</p>\n</body></html>'
Mon Jun 11 18:13:22 2018

所以:

  • urlopen 等待 3 秒,直到标题部分结束
  • first read ( read(10)) 为消息的第一部分再等待 2 秒
  • 第二次读取 ( read()) 再等待 5 秒以等待消息结束

推荐阅读