首页 > 解决方案 > Python 将 urllib3.response.HTTPResponse 转换为 httplib.HTTPResponse

问题描述

我正在尝试从 httplib 迁移到 urllib3。urllib3.PoolManager返回urllib3.response.HTTPResponsehttplib.HTTPConnection返回httplib.HTTPResponse

import SocketServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import threading
import httplib
import urllib3

class S(SimpleHTTPRequestHandler):

    def html(self):
        content = "<html><body><h1>Hi</h1></body></html>"
        return content.encode("utf8")

    def do_GET(self):
        self.wfile.write(self.html())


def run_server(handler_class=S, addr="localhost", port=8000):
    httpd = SocketServer.TCPServer((addr, port), handler_class)
    print('Starting httpd...')
    httpd.serve_forever()

t = threading.Thread(target=run_server)
t.setDaemon(True)
t.start()

http = httplib.HTTPConnection("localhost", 8000)
http.request('GET', '/')
r = http.getresponse()
print str(r), r.status, r.read()

http = urllib3.connectionpool.HTTPConnection("localhost", 8000)
http.request('GET', '/')
r = http.getresponse()
print r, r.status, r.read()

http = urllib3.PoolManager()
r = http.request('GET', 'http://localhost:8000/')
print r, r.status, r.data

输出

Starting httpd...
<httplib.HTTPResponse instance at 0x10cc01c68> 200 <html><body><h1>Hi</h1></body></html>
<httplib.HTTPResponse instance at 0x10cc03b48> 200 <html><body><h1>Hi</h1></body></html>
<urllib3.response.HTTPResponse object at 0x10bfa3f10> 200 <html><body><h1>Hi</h1></body></html>

我正在处理多个调用者期望的遗留代码库httplib.HTTPResponse。有人可以让我知道有没有办法httplib.HTTPResponse在使用时获得,urllib3.PoolManager或者是否有一个转换器可以用来转换urllib3.response.HTTPResponsehttplib.HTTPResponse以便我可以将更改最小化到几个基类?

标签: pythonpython-2.7

解决方案


推荐阅读