Skip to content

Commit

Permalink
Lazy load requests in Transmission class (#121)
Browse files Browse the repository at this point in the history
* When using alternate transmission implementations like FileTransmission there
     is no need to import requests, as this just adds additional initialization time.
     Initialization time is important especially when running in the context of a Lambda function
     where cold starts will always need to incur this additional load time. Currently
     beeline-python uses libhoney Client which imports Transmission and therefore
     always imports requests.
  • Loading branch information
danvendia authored Jul 12, 2022
1 parent 7f5b3ec commit 44f0731
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
2 changes: 1 addition & 1 deletion libhoney/test_transmission.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def test_args(self):

def test_user_agent_addition(self):
''' ensure user_agent_addition is included in the User-Agent header '''
with mock.patch('libhoney.transmission.requests.Session') as m_session:
with mock.patch('libhoney.transmission.Transmission._get_requests_session') as m_session:
transmission.Transmission(
user_agent_addition='foo/1.0', gzip_enabled=False)
expected = "libhoney-py/" + libhoney.version.VERSION + " foo/1.0"
Expand Down
9 changes: 7 additions & 2 deletions libhoney/transmission.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import io
import json
import threading
import requests
import statsd
import sys
import time
Expand Down Expand Up @@ -48,7 +47,7 @@ def __init__(self, max_concurrent_batches=10, block_on_send=False,
if user_agent_addition:
user_agent += " " + user_agent_addition

session = requests.Session()
session = self._get_requests_session()
session.headers.update({"User-Agent": user_agent})
if self.gzip_enabled:
session.headers.update({"Content-Encoding": "gzip"})
Expand All @@ -68,6 +67,12 @@ def __init__(self, max_concurrent_batches=10, block_on_send=False,
if debug:
self._init_logger()

@staticmethod
def _get_requests_session():
# lazy load requests only when needed
import requests # pylint: disable=import-outside-toplevel
return requests.Session()

def _init_logger(self):
import logging # pylint: disable=bad-option-value,import-outside-toplevel
self._logger = logging.getLogger('honeycomb-sdk-xmit')
Expand Down

0 comments on commit 44f0731

Please sign in to comment.