The Python “requests” library is currently all the rage, because of the beautiful interface that it provides for making HTTP requests — but beneath it there seems to be many layers of indirection — sessions, HTTP adapters, and finally the mechanics of urllib3.
Where in this stack of abstractions is the right place to intervene if I already hold an open socket, and want to use “requests” to send an HTTP response down that socket and receive a reply back?
Without some kind of intervention (or customization?), the stack will try to create a new TCP/IP socket for me, but in my particular application my code is not called until a connection has already been established on my behalf, so I will need to convince Requests to talk on that existing socket if I want to be able to use Requests' features.
The Requests library:
The following code needs requests from git (especially
requests.packages.urllib3.poolmanager.PoolManager._new_pool()
)I tested it using
ncat -v -l 127.0.0.1 8000
The problem is the fact, that the connection isn't opened by urllib3 but by httplib from the standard library.
Edit:
Or direct monkeypatching of the connectionpool:
Go straight to the
urllib3
library; it holds a connection pool in theurllib3.connectionpool
module.You could replace the pool or adjust it by hacking the
poolmanager
module perhaps.