Merge pull request #982 from vlaci/master
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Added support for persistent connections (keep-alive) in proxy mode
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 23e6f53, 5eb7887 · Browse files · 3 files·+127 added−10 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+127 added−10 removed
- tests:+111 added−0 removed
- other:+16 added−10 removed
Provenance
- Commit
33eb76f- Tree
1a49cd5- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
23e6f53- Parent 2
5eb7887
3 files changed+127 added−10 removed
modified:requests/models.py+16 added-10 removed
555 unmodified lines556 no_proxy = filter(lambda x: x.strip(), self.proxies.get('no', '').split(','))557 proxy = self.proxies.get(_p.scheme)558 559 if proxy and not any(map(_p.hostname.endswith, no_proxy)):560- conn = poolmanager.proxy_from_url(proxy)560+ conn = poolmanager.ProxyManager(self.get_connection_for_url(proxy))561 _proxy = urlparse(proxy)562 if '@' in _proxy.netloc:563 auth, url = _proxy.netloc.split('@', 1)564 self.proxy_auth = HTTPProxyAuth(*auth.split(':', 1))565 r = self.proxy_auth(self)566 self.__dict__.update(r.__dict__)567 else:568- # Check to see if keep_alive is allowed.569- try:570- if self.config.get('keep_alive'):571- conn = self._poolmanager.connection_from_url(url)572- else:573- conn = connectionpool.connection_from_url(url)574- self.headers['Connection'] = 'close'575- except LocationParseError as e:576- raise InvalidURL(e)568+ conn = self.get_connection_for_url(url)569 570+ if not self.config.get('keep_alive'):571+ self.headers['Connection'] = 'close'572+573 if url.startswith('https') and self.verify:574 575 cert_loc = None576 89 unmodified lines666 self.response.content667 668 return self.sent669 670+ def get_connection_for_url(self, url):671+ # Check to see if keep_alive is allowed.672+ try:673+ if self.config.get('keep_alive'):674+ conn = self._poolmanager.connection_from_url(url)675+ else:676+ conn = connectionpool.connection_from_url(url)677+ return conn678+ except LocationParseError as e:679+ raise InvalidURL(e)680 681+682 class Response(object):683 """The core :class:`Response <Response>` object. All684 :class:`Request <Request>` objects contain a685 :class:`response <Response>` attribute, which is an instance234 unmodified linesadded:tests/dummy_server.py+46 added
1+import asyncore2+import threading3+import socket4+5+class HttpServer(threading.Thread):6+ def __init__(self, port):7+ threading.Thread.__init__(self)8+ self.dispatcher = HttpServerDispatcher(port)9+10+ def run(self):11+ asyncore.loop()12+13+ @property14+ def connection_count(self):15+ return self.dispatcher.connection_count16+17+ def close(self):18+ asyncore.close_all()19+20+class HttpServerDispatcher(asyncore.dispatcher):21+ def __init__(self, port):22+ asyncore.dispatcher.__init__(self)23+ self.connected = False24+ self.create_socket(socket.AF_INET, socket.SOCK_STREAM)25+ self.bind(('127.0.0.1', port))26+ self.listen(1)27+ self.connection_count = 028+29+ def handle_accept(self):30+ self.connection_count += 131+ self.handler = RequestHandler(self.accept()[0])32+33+ def handle_close(self):34+ self.close()35+36+37+class RequestHandler(asyncore.dispatcher_with_send):38+ def __init__(self, sock):39+ asyncore.dispatcher_with_send.__init__(self, sock)40+ self.response = ("HTTP/1.1 200 OK\r\n"41+ "Connection: keep-alive\r\n"42+ "Content-Length: 0\r\n\r\n")43+44+ def handle_read(self):45+ self.recv(1024)46+ self.send(self.response)added:tests/test_keep_alive.py+65 added
1+#!/usr/bin/env python2+# -*- coding: utf-8 -*-3+4+import os5+import sys6+import unittest7+8+# Path hack.9+sys.path.insert(0, os.path.abspath('..'))10+import requests11+import dummy_server12+13+class KeepAliveTests(unittest.TestCase):14+ server_and_proxy_port = 123415+ request_count = 216+ url = 'http://localhost:{0}'.format(server_and_proxy_port)17+ proxies={'http': url}18+19+ def setUp(self):20+ self.session = requests.session()21+ self.proxy_server = dummy_server.HttpServer(self.server_and_proxy_port)22+ self.proxy_server.start()23+24+ def tearDown(self):25+ self.proxy_server.close()26+27+ def test_keep_alive_with_direct_connection(self):28+ self.make_requests()29+ self.check_each_request_are_in_same_connection()30+31+ def test_no_keep_alive_with_direct_connection(self):32+ self.disable_keep_alive_in_session()33+ self.make_requests()34+ self.check_each_request_are_in_different_connection()35+36+ def test_keep_alive_with_proxy_connection(self):37+ self.make_proxy_requests()38+ self.check_each_request_are_in_same_connection()39+40+ def test_no_keep_alive_with_proxy_connection(self):41+ self.disable_keep_alive_in_session()42+ self.make_proxy_requests()43+ self.check_each_request_are_in_different_connection()44+45+ def make_proxy_requests(self):46+ self.make_requests(self.proxies)47+48+ def make_requests(self, proxies=None):49+ for _ in xrange(self.request_count):50+ self.session.get(self.url, proxies=proxies).text51+52+ def check_each_request_are_in_same_connection(self):53+ """Keep-alive requests open a single connection to the server."""54+ self.assertEqual(self.proxy_server.connection_count, 1)55+56+ def check_each_request_are_in_different_connection(self):57+ """Keep-alive requests open a single connection to the server."""58+ self.assertEqual(self.proxy_server.connection_count, self.request_count)59+60+ def disable_keep_alive_in_session(self):61+ self.session.config['keep_alive'] = False62+63+64+if __name__ == '__main__':65+ unittest.main()