Building Multi Page Web App Using Streamlit
In the previous blog we saw how to install streamlit and build a simple hello world app. In this blog we will see how to build a multi page web app using streamlit and then create a general framework to build multi page apps.
Creating a Multi Page App:
As mentioned already streamlit does not have a implicit feature to add a tab for a new page in a single page, but using some existing features we can create a work around for building multi page apps.
We can create multiple apps and navigate across each of them in a main app using a radio button. Let’s see how to do that.
- Create
app1.py
andapp2.py
.
# app1.py
import streamlit as st
def app():
st.title('APP1')
st.write('Welcome to app1')
# app2.py
import streamlit as st
def app():
st.title('APP2')
st.write('Welcome to app2')
2. Create a main app app.py
and add a navigator using radio buttons.
#app.pyimport app1
import app2
import streamlit as stPAGES = {
"App1": app1,
"App2": app2
}st.sidebar.title('Navigation')
selection = st.sidebar.radio("Go to", list(PAGES.keys()))
page = PAGES[selection]
page.app()
Now you run the app.py
to access and navigate through both the apps.
Though the code looks simple it is hard to maintain when the no of pages increase. Hence using the above idea i have created a framework multiapp.py
(click here to view the code) through which we can create a multi page app which is simple and maintainable as shown below:
Steps to create the app:
- Import class
MultiApp
from multiapp.py in your app and create a new instance for it. - Add a new app using the class function
add_app(title, func)
which takes title and function as the argument. - Finally run the multi app using class function
run()
.
Below are examples to create a multi page app using the above framework.
# new_app1.py
from multiapp import MultiApp
import streamlit as stdef foo():
st.title("Hello Foo")
def bar():
st.title("Hello Bar")app = MultiApp()app.add_app("Foo", foo)
app.add_app("Bar", bar)app.run()
It is also possible keep each application in a separate file.
# new_app2.py
import foo
import bar
from multiapp import MultiAppapp = MultiApp()app.add_app("Foo", foo.app)
app.add_app("Bar", bar.app)app.run()
Clone the below GitHub repository and run the app to see a sample multi page web app as shown below.
https://github.com/upraneelnihar/streamlit-multiapps