@@ -60,6 +60,7 @@ def __init__(
6060 ip : Optional [str ] = None ,
6161 apilytics_integration : Optional [str ] = None ,
6262 integrated_library : Optional [str ] = None ,
63+ prevent_send_on_exit : bool = False ,
6364 ) -> None :
6465 """
6566 Initialize the context manager with info from the HTTP request object.
@@ -79,6 +80,8 @@ def __init__(
7980 e.g. "apilytics-python-django". No need to pass this when calling from user code.
8081 integrated_library: Name and version of the integration that this is used in,
8182 e.g. "django/3.2.1". No need to pass this when calling from user code.
83+ prevent_send_on_exit: Don't immediately send the metrics when the context
84+ manager exits. Useful for advanced deferred sending scenarios.
8285 """
8386 self ._api_key = api_key
8487 self ._path = path
@@ -96,6 +99,8 @@ def __init__(
9699 library = integrated_library or "" ,
97100 )
98101
102+ self ._prevent_send_on_exit = prevent_send_on_exit
103+
99104 def __enter__ (self ) -> "ApilyticsSender" :
100105 """Start the timer, measuring how long the ``with`` block takes to execute."""
101106 self ._start_time_ns = time .perf_counter_ns ()
@@ -107,15 +112,9 @@ def __exit__(
107112 exc_val : Optional [BaseException ],
108113 exc_tb : Optional [types .TracebackType ],
109114 ) -> None :
110- """Send metrics to Apilytics in a fire-and-forget background task."""
111- self ._end_time_ns = time .perf_counter_ns ()
112- if not hasattr (self , "_executor" ):
113- # Use only a single background thread and share the pool to minimize
114- # resource hogging.
115- self .__class__ ._executor = concurrent .futures .ThreadPoolExecutor (
116- max_workers = 1
117- )
118- self ._executor .submit (self ._send_metrics )
115+ if self ._prevent_send_on_exit :
116+ return
117+ self .send ()
119118
120119 def set_response_info (
121120 self , * , status_code : Optional [int ] = None , response_size : Optional [int ] = None
@@ -133,6 +132,17 @@ def set_response_info(
133132 self ._status_code = status_code
134133 self ._response_size = response_size
135134
135+ def send (self ) -> None :
136+ """Send metrics to Apilytics in a fire-and-forget background task."""
137+ self ._end_time_ns = time .perf_counter_ns ()
138+ if not hasattr (self , "_executor" ):
139+ # Use only a single background thread and share the pool to minimize
140+ # resource hogging.
141+ self .__class__ ._executor = concurrent .futures .ThreadPoolExecutor (
142+ max_workers = 1
143+ )
144+ self ._executor .submit (self ._send_metrics )
145+
136146 def _send_metrics (self ) -> None :
137147 memory_usage , memory_total = _get_used_and_total_memory ()
138148 cpu_usage = _get_cpu_usage ()
0 commit comments