Skip to content

Commit d7976a2

Browse files
committed
feat(streamlit): setup django during init
so e.g. Django models can be queried from Streamlit apps
1 parent 9e5cf8a commit d7976a2

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

streamlit_app/main.py

+13
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import logging
2+
import os
23

4+
import django
35
import streamlit as st
46

57
from streamlit_app.utils import discover_apps
@@ -8,9 +10,20 @@
810
logger = logging.getLogger(__name__)
911

1012

13+
def django_setup():
14+
"""
15+
Configures Django in case it is not running in the same environment. Should be called before using e.g. PeMS models.
16+
"""
17+
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pems.settings")
18+
19+
django.setup()
20+
21+
1122
def main():
1223
logger.info("Streamlit initializing")
1324

25+
django_setup()
26+
1427
# find apps in the ./streamlit_app/apps directory and subdirectories
1528
# apps are python modules with a name starting with "app_"
1629
apps = discover_apps()

tests/pytest/streamlit_app/test_main.py

+2
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,13 @@ def test_main(mocker, monkeypatch, nav_option, expected_nav):
1919
else:
2020
monkeypatch.delenv(nav_key, False)
2121

22+
mock_django = mocker.patch("streamlit_app.main.django.setup")
2223
mock_discover = mocker.patch("streamlit_app.main.discover_apps", return_value=apps)
2324
mock_navigate = mocker.patch("streamlit_app.main.st.navigation")
2425

2526
main.main()
2627

28+
mock_django.assert_called_once()
2729
mock_discover.assert_called_once()
2830
mock_navigate.assert_called_once_with(apps, position=expected_nav)
2931
mock_navigate.return_value.run.assert_called_once()

0 commit comments

Comments
 (0)