Skip to content

Commit 54ad220

Browse files
SNOW-1762538 add detecting running inside a Jupyter notebook for collecting usage stats (#2290)
1 parent 8350f8b commit 54ad220

File tree

2 files changed

+32
-8
lines changed

2 files changed

+32
-8
lines changed

src/snowflake/connector/connection.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -499,10 +499,9 @@ def __init__(
499499
is_kwargs_empty = not kwargs
500500

501501
if "application" not in kwargs:
502-
if ENV_VAR_PARTNER in os.environ.keys():
503-
kwargs["application"] = os.environ[ENV_VAR_PARTNER]
504-
elif "streamlit" in sys.modules:
505-
kwargs["application"] = "streamlit"
502+
app = self._detect_application()
503+
if app:
504+
kwargs["application"] = app
506505

507506
if "insecure_mode" in kwargs:
508507
warn_message = "The 'insecure_mode' connection property is deprecated. Please use 'disable_ocsp_checks' instead"
@@ -2283,3 +2282,17 @@ def _check_oauth_parameters(self) -> None:
22832282
"errno": ER_INVALID_VALUE,
22842283
},
22852284
)
2285+
2286+
@staticmethod
2287+
def _detect_application() -> None | str:
2288+
if ENV_VAR_PARTNER in os.environ.keys():
2289+
return os.environ[ENV_VAR_PARTNER]
2290+
if "streamlit" in sys.modules:
2291+
return "streamlit"
2292+
if all(
2293+
(jpmod in sys.modules)
2294+
for jpmod in ("ipykernel", "jupyter_core", "jupyter_client")
2295+
):
2296+
return "jupyter_notebook"
2297+
if "snowbooks" in sys.modules:
2298+
return "snowflake_notebook"

test/unit/test_connection.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -194,12 +194,23 @@ def test_partner_env_var(mock_post_requests):
194194

195195

196196
@pytest.mark.skipolddriver
197-
def test_imported_module(mock_post_requests):
198-
with patch.dict(sys.modules, {"streamlit": "foo"}):
199-
assert fake_connector().application == "streamlit"
197+
@pytest.mark.parametrize(
198+
"sys_modules,application",
199+
[
200+
({"streamlit": None}, "streamlit"),
201+
(
202+
{"ipykernel": None, "jupyter_core": None, "jupyter_client": None},
203+
"jupyter_notebook",
204+
),
205+
({"snowbooks": None}, "snowflake_notebook"),
206+
],
207+
)
208+
def test_imported_module(mock_post_requests, sys_modules, application):
209+
with patch.dict(sys.modules, sys_modules):
210+
assert fake_connector().application == application
200211

201212
assert (
202-
mock_post_requests["data"]["CLIENT_ENVIRONMENT"]["APPLICATION"] == "streamlit"
213+
mock_post_requests["data"]["CLIENT_ENVIRONMENT"]["APPLICATION"] == application
203214
)
204215

205216

0 commit comments

Comments
 (0)