Skip to content

Commit 007e770

Browse files
committed
allow lazy init, fix tests
1 parent 17b87be commit 007e770

File tree

1 file changed

+28
-25
lines changed

1 file changed

+28
-25
lines changed

sentry_sdk/spotlight.py

Lines changed: 28 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def capture_envelope(self, envelope):
8686
]
8787

8888
class SpotlightMiddleware(MiddlewareMixin):
89-
_spotlight_script: Optional[str]
89+
__spotlight_script: Optional[str] = None
9090
_spotlight_url: str
9191

9292
def __init__(self, get_response):
@@ -104,29 +104,32 @@ def __init__(self, get_response):
104104
)
105105
return None
106106
# Spotlight URL has a trailing `/stream` part at the end so split it off
107-
spotlight_url = self._spotlight_url = urllib.parse.urljoin(
108-
spotlight_client.url, "../"
109-
)
107+
self._spotlight_url = urllib.parse.urljoin(spotlight_client.url, "../")
108+
109+
@property
110+
def spotlight_script(self):
111+
# type: (Self) -> Optional[str]
112+
if self.__spotlight_script is None:
113+
try:
114+
spotlight_js_url = urllib.parse.urljoin(
115+
self._spotlight_url, SPOTLIGHT_JS_ENTRY_PATH
116+
)
117+
req = urllib.request.Request(
118+
spotlight_js_url,
119+
method="HEAD",
120+
)
121+
urllib.request.urlopen(req)
122+
self.__spotlight_script = SPOTLIGHT_JS_SNIPPET_PATTERN.format(
123+
spotlight_js_url
124+
)
125+
except urllib.error.URLError as err:
126+
sentry_logger.debug(
127+
"Cannot get Spotlight JS to inject at %s. SpotlightMiddleware will not be very useful.",
128+
spotlight_js_url,
129+
exc_info=err,
130+
)
110131

111-
try:
112-
spotlight_js_url = urllib.parse.urljoin(
113-
spotlight_url, SPOTLIGHT_JS_ENTRY_PATH
114-
)
115-
req = urllib.request.Request(
116-
spotlight_js_url,
117-
method="HEAD",
118-
)
119-
urllib.request.urlopen(req)
120-
self._spotlight_script = SPOTLIGHT_JS_SNIPPET_PATTERN.format(
121-
spotlight_js_url
122-
)
123-
except urllib.error.URLError as err:
124-
sentry_logger.debug(
125-
"Cannot get Spotlight JS to inject at %s. SpotlightMiddleware will not be very useful.",
126-
spotlight_js_url,
127-
exc_info=err,
128-
)
129-
self._spotlight_script = None
132+
return self.__spotlight_script
130133

131134
def process_response(self, _request, response):
132135
# type: (Self, HttpRequest, HttpResponse) -> Optional[HttpResponse]
@@ -143,12 +146,12 @@ def process_response(self, _request, response):
143146
encoding = "utf-8"
144147

145148
if (
146-
self._spotlight_script is not None
149+
self.spotlight_script is not None
147150
and not response.streaming
148151
and content_type == "text/html"
149152
):
150153
content_length = len(response.content)
151-
injection = self._spotlight_script.encode(encoding)
154+
injection = self.spotlight_script.encode(encoding)
152155
injection_site = next(
153156
(
154157
idx

0 commit comments

Comments
 (0)