Skip to content
Myr

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

3 files+127 added−10 removed

modified:requests/models.py+16 added-10 removed
555 unmodified lines
556 no_proxy = filter(lambda x: x.strip(), self.proxies.get('no', '').split(','))557 proxy = self.proxies.get(_p.scheme)558559 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)569570 if not self.config.get('keep_alive'):571 self.headers['Connection'] = 'close'572573 if url.startswith('https') and self.verify:574575 cert_loc = None576
89 unmodified lines
666 self.response.content667668 return self.sent669670 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)680681682class Response(object):683 """The core :class:`Response <Response>` object. All684 :class:`Request <Request>` objects contain a685 :class:`response <Response>` attribute, which is an instance
234 unmodified lines
added:tests/dummy_server.py+46 added
1import asyncore2import threading3import socket45class HttpServer(threading.Thread):6 def __init__(self, port):7 threading.Thread.__init__(self)8 self.dispatcher = HttpServerDispatcher(port)910 def run(self):11 asyncore.loop()1213 @property14 def connection_count(self):15 return self.dispatcher.connection_count1617 def close(self):18 asyncore.close_all()1920class 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 = 02829 def handle_accept(self):30 self.connection_count += 131 self.handler = RequestHandler(self.accept()[0])3233 def handle_close(self):34 self.close()353637class 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")4344 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 -*-34import os5import sys6import unittest78# Path hack.9sys.path.insert(0, os.path.abspath('..'))10import requests11import dummy_server1213class 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}1819 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()2324 def tearDown(self):25 self.proxy_server.close()2627 def test_keep_alive_with_direct_connection(self):28 self.make_requests()29 self.check_each_request_are_in_same_connection()3031 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()3536 def test_keep_alive_with_proxy_connection(self):37 self.make_proxy_requests()38 self.check_each_request_are_in_same_connection()3940 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()4445 def make_proxy_requests(self):46 self.make_requests(self.proxies)4748 def make_requests(self, proxies=None):49 for _ in xrange(self.request_count):50 self.session.get(self.url, proxies=proxies).text5152 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)5556 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)5960 def disable_keep_alive_in_session(self):61 self.session.config['keep_alive'] = False626364if __name__ == '__main__':65 unittest.main()