python将urllib3.response.httpresponse转换为httplib.httpresponse

p1tboqfb  于 2021-08-25  发布在  Java
关注(0)|答案(0)|浏览(338)

我正在尝试从httplib迁移到urllib3。 urllib3.PoolManager 返回 urllib3.response.HTTPResponse 鉴于 httplib.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 这样我就可以将更改最小化到几个基类?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题