Skip to content

Commit 0533097

Browse files
SNOW-1762538 add detecting running inside a Jupyter notebook for collecting usage stats (#2290)
(cherry picked from commit 54ad220)
1 parent 4a5e7e6 commit 0533097

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
@@ -459,10 +459,9 @@ def __init__(
459459
is_kwargs_empty = not kwargs
460460

461461
if "application" not in kwargs:
462-
if ENV_VAR_PARTNER in os.environ.keys():
463-
kwargs["application"] = os.environ[ENV_VAR_PARTNER]
464-
elif "streamlit" in sys.modules:
465-
kwargs["application"] = "streamlit"
462+
app = self._detect_application()
463+
if app:
464+
kwargs["application"] = app
466465

467466
if "insecure_mode" in kwargs:
468467
warn_message = "The 'insecure_mode' connection property is deprecated. Please use 'disable_ocsp_checks' instead"
@@ -2146,3 +2145,17 @@ def is_valid(self) -> bool:
21462145
except Exception as e:
21472146
logger.debug("session could not be validated due to exception: %s", e)
21482147
return False
2148+
2149+
@staticmethod
2150+
def _detect_application() -> None | str:
2151+
if ENV_VAR_PARTNER in os.environ.keys():
2152+
return os.environ[ENV_VAR_PARTNER]
2153+
if "streamlit" in sys.modules:
2154+
return "streamlit"
2155+
if all(
2156+
(jpmod in sys.modules)
2157+
for jpmod in ("ipykernel", "jupyter_core", "jupyter_client")
2158+
):
2159+
return "jupyter_notebook"
2160+
if "snowbooks" in sys.modules:
2161+
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)