mirror of
https://github.com/kennethreitz/requests.git
synced 2026-06-05 22:50:18 +00:00
base adapter
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
requests.adapters
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
This module contains the transport adapters that Requests uses to define
|
||||
and maintain connections.
|
||||
"""
|
||||
import os
|
||||
from .packages.urllib3.poolmanager import PoolManager
|
||||
from .utils import DEFAULT_CA_BUNDLE_PATH
|
||||
|
||||
|
||||
DEFAULT_POOLSIZE = 10
|
||||
DEFAULT_RETRIES = 0
|
||||
|
||||
|
||||
class BaseAdapter(object):
|
||||
"""The Base Transport Adapter"""
|
||||
|
||||
def __init__(self):
|
||||
super(BaseAdapter, self).__init__()
|
||||
|
||||
def send(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def close(self):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class HTTPAdapter(BaseAdapter):
|
||||
"""Built-In HTTP Adapter for Urllib3."""
|
||||
def __init__(self,
|
||||
pool_connections=DEFAULT_POOLSIZE,
|
||||
pool_maxsize=DEFAULT_POOLSIZE):
|
||||
self.max_retries = DEFAULT_RETRIES
|
||||
self.config = {}
|
||||
|
||||
super(HTTPAdapter, self).__init__()
|
||||
|
||||
self.init_poolmanager(pool_connections, pool_maxsize)
|
||||
|
||||
def init_poolmanager(self, connections, maxsize):
|
||||
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize)
|
||||
|
||||
def cert_verify(self, conn, verify, cert):
|
||||
if url.startswith('https') and self.verify:
|
||||
|
||||
cert_loc = None
|
||||
|
||||
# Allow self-specified cert location.
|
||||
if self.verify is not True:
|
||||
cert_loc = self.verify
|
||||
|
||||
# Look for configuration.
|
||||
if not cert_loc and self.config.get('trust_env'):
|
||||
cert_loc = os.environ.get('REQUESTS_CA_BUNDLE')
|
||||
|
||||
# Curl compatibility.
|
||||
if not cert_loc and self.config.get('trust_env'):
|
||||
cert_loc = os.environ.get('CURL_CA_BUNDLE')
|
||||
|
||||
if not cert_loc:
|
||||
cert_loc = DEFAULT_CA_BUNDLE_PATH
|
||||
|
||||
if not cert_loc:
|
||||
raise Exception("Could not find a suitable SSL CA certificate bundle.")
|
||||
|
||||
conn.cert_reqs = 'CERT_REQUIRED'
|
||||
conn.ca_certs = cert_loc
|
||||
else:
|
||||
conn.cert_reqs = 'CERT_NONE'
|
||||
conn.ca_certs = None
|
||||
|
||||
if self.cert:
|
||||
if len(self.cert) == 2:
|
||||
conn.cert_file = self.cert[0]
|
||||
conn.key_file = self.cert[1]
|
||||
else:
|
||||
conn.cert_file = self.cert
|
||||
|
||||
def close(self):
|
||||
"""Dispose of any internal state.
|
||||
|
||||
Currently, this just closes the PoolManager, which closes pooled
|
||||
connections.
|
||||
"""
|
||||
self.poolmanager.clear()
|
||||
|
||||
def send(self, request, timeout, verify, cert):
|
||||
"""Sends PreparedRequest object. Returns Response object."""
|
||||
|
||||
conn = self._poolmanager.connection_from_url(request.url)
|
||||
self.cert_verify(conn, verify, cert)
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user