<commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import
from requests.exceptions import RequestException
from time import time
import random
import threading
import base64
import requests
from .exceptions import NoServerAvailable
from .fakettypes import Method, RestResponse
from . import logger

__all__ = ['connect', 'connect_thread_local']

DEFAULT_SERVER = ("http", "127.0.0.1", 9200)


class ClientTransport(object):
    """Encapsulation of a client session."""

    def __init__(self, server, timeout, recycle, basic_auth=None):
        connection_type, host, port = server
        self.server_uri = '%s://%s:%s' % (connection_type, host, port)
        self.timeout = timeout
        self.headers = {}
        if recycle:
            self.recycle = time() + recycle + random.uniform(0, recycle * 0.1)
        else:
            self.recycle = None
        if basic_auth:
            username = basic_auth.get('username')
            password = <PASSWORD>_auth.get('password')
            base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
            self.headers["Authorization"] = 'Basic %s' % base64string

    def execute(self, request):
        """Execute a request and return a response"""
        headers = self.headers.copy()
        headers.update(request.headers)
        response = requests.session().request(
            method=Method._VALUES_TO_NAMES[request.method],
            url=self.server_uri + request.uri,
            params=request.parameters,
            data=request.body,
            headers=request.headers,
            timeout=self.timeout)
        return RestResponse(status=response.status_code,
                            body=response.content,
                            headers=response.headers)


def connect(servers=None, framed_transport=False, timeout=None,
            retry_time=60, recycle=None, round_robin=None,
            max_retries=3, basic_auth=None):
    """
    Constructs a single ElasticSearch connection. Connects to a randomly chosen
    server on the list.

    If the connection fails, it will attempt to connect to each server on the
    list in turn until one succeeds. If it is unable to find an active server,
    it will throw a NoServerAvailable exception.

    Failing servers are kept on a separate list and eventually retried, no
    sooner than `retry_time` seconds after failure.

    Parameters
    ----------
    servers : [server]
              List of ES servers with format: "hostname:port"<commit_msg>Use a single global ConnectionPool instead of initializing it on every execute call<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import
from requests.exceptions import RequestException
from time import time
import random
import threading
import base64
import requests
from .exceptions import NoServerAvailable
from .fakettypes import Method, RestResponse
from . import logger

__all__ = ['connect', 'connect_thread_local']

DEFAULT_SERVER = ("http", "127.0.0.1", 9200)
SESSION = requests.session()

class ClientTransport(object):
    """Encapsulation of a client session."""

    def __init__(self, server, timeout, recycle, basic_auth=None):
        connection_type, host, port = server
        self.server_uri = '%s://%s:%s' % (connection_type, host, port)
        self.timeout = timeout
        self.headers = {}
        if recycle:
            self.recycle = time() + recycle + random.uniform(0, recycle * 0.1)
        else:
            self.recycle = None
        if basic_auth:
            username = basic_auth.get('username')
            password = basic_auth.get('password')
            base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
            self.headers["Authorization"] = 'Basic %s' % base64string

    def execute(self, request):
        """Execute a request and return a response"""
        headers = self.headers.copy()
        headers.update(request.headers)
        response = SESSION.request(
            method=Method._VALUES_TO_NAMES[request.method],
            url=self.server_uri + request.uri,
            params=request.parameters,
            data=request.body,
            headers=request.headers,
            timeout=self.timeout)
        return RestResponse(status=response.status_code,
                            body=response.content,
                            headers=response.headers)


def connect(servers=None, framed_transport=False, timeout=None,
            retry_time=60, recycle=None, round_robin=None,
            max_retries=3, basic_auth=None):
    """
    Constructs a single ElasticSearch connection. Connects to a randomly chosen
    server on the list.

    If the connection fails, it will attempt to connect to each server on the
    list in turn until one succeeds. If it is unable to find an active server,
    it will throw a NoServerAvailable exception.

    Failing servers are kept on a separate list and eventually retried, no
    sooner than `retry_time` seconds after failure.

    Parameters
    ----------
    servers : [server]
              List of ES servers with format: "hostname:port"
{'fraction_non_alphanumeric': 0.09496879875195008, 'fraction_numerical': 0.01014040561622465, 'mean_word_length': 2.6714387974230496, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2937376', 'n_tokens_mistral': 1383, 'n_tokens_neox': 1357, 'n_words': 421}