StreamlitAPIException

This error keeps occurring on my deployed app. I am not getting this error while running the app on my local.

streamlit.errors.StreamlitAPIException: `set_page_config()` can only be called once per app, and must be called as the first Streamlit command in your script.
For more information refer to the [docs](https://docs.streamlit.io/en/stable/api.html#streamlit.set_page_config).
2021-10-05 12:09:07.065 Uncaught app exception
Traceback (most recent call last):
  File "/home/appuser/venv/lib/python3.7/site-packages/streamlit/script_runner.py", line 354, in _run_script
    exec(code, module.__dict__)
  File "/app/modern_millennial_market_mapping/app.py", line 294, in <module>
    'About': "# > Creator: Gordon D. Pisciotta  ·  4M  ·  [modern.millennial.market.mapping]",
  File "/home/appuser/venv/lib/python3.7/site-packages/streamlit/commands/page_config.py", line 144, in set_page_config
    ctx.enqueue(msg)
  File "/home/appuser/venv/lib/python3.7/site-packages/streamlit/report_thread.py", line 101, in enqueue
    + "(https://docs.streamlit.io/en/stable/api.html#streamlit.set_page_config)."
streamlit.errors.StreamlitAPIException: `set_page_config()` can only be called once per app, and must be called as the first Streamlit command in your script.
For more information refer to the [docs](https://docs.streamlit.io/en/stable/api.html#streamlit.set_page_config).

Hi @ramraider011235, welcome back to the community! Are you able to post your code repo?

Hey, I am having this same problem as of this morning (Streamlit 1.0.0)

I am using a multipage app and st.set_page_config is only being called once from the streamlit_app.py

I only get an error when I make code changes (with auto refresh on or off). If I hit ‘R’ after the error, it reloads the app just fine, but I loose where I was at and any inputs.

Oddly it wasn’t doing this until I removed some of the unused imports from the main app.

Tested on Firefox and Edge

import streamlit as st
import src.utils.utils as utils
import src.data_analysis
import src.data_processing
import src.data_augmentation
import src.data_balancing

# Aesthetics
mimiric_logo = "https://www.northernpaganism.org/assets/images/Mimir/well1.JPG"

st.set_page_config(page_title="Mimiric: A tool for ML data",
                   page_icon=mimiric_logo,
                   layout='wide',
                   initial_sidebar_state='auto')

###Begin of main application
###Begin of main application
def main():
    st.sidebar.image([mimiric_logo], width=130, caption=["Mimiric's Well"], output_format="PNG")
    """
    # :skull: Welcome to Mimiric :skull:

    """
    st.write("---")
    # Module section
    modules_available = {
           "Data Analysis": src.data_analysis,
           "Data Balancing": src.data_balancing,
           "Data Processing": src.data_processing,
           "Data Augmentation": src.data_augmentation,
            }


    with st.sidebar:
        module_select = st.radio(label="Training Data Modules", options=modules_available.keys())

    st.title(f"{module_select}")

if __name__ == "__main__":
    main()

Hello Randy Thank you for getting back on this issue. I cant even begin to explain how many different configurations I have tried to make this work correctly. Then this evening I was getting ready to send over my code to get a second set of eyes and I had one last idea on what might be causing the issue. The message says it has to be the first streamlit command called in the app and only called one time. I followed both of those rules even searching my entire repository for any other mention of this command to ensure I didnt accidently add it somewhere.

Tonight I had the thought to put the st.set_page_config() command at the very top of my app.py file.
On the very first line before anything else I entered this:

1 import streamlit as st
2 st.set_page_config(
page_title=xxx,
page_icon=chart_with_upwards_trend,
layout=“wide”,
initial_sidebar_state=“auto”,
menu_items=None,
)

When I ran it on the local no issues. I pushed it up to my github repository for the deployed app to access then rebooted the application from the https://share.streamlit.io/ app management page. And the issue was resolved. I hope this helps!

import streamlit as st
st.set_page_config(
    page_title="4M",
    page_icon="chart_with_upwards_trend",
    layout="wide",
    initial_sidebar_state="expanded",
    menu_items={
        'Get Help': 'https://www.extremelycoolapp.com/help',
        'Report a bug': "https://www.extremelycoolapp.com/bug",
        'About': "# > Creator: Gordon D. Pisciotta  ·  4M  ·  [modern.millennial.market.mapping]",
    }
)
st.markdown(
    f""" 
    <style>
    #.reportview-container .main .block-container{{
        padding-top: {1.3}rem;
        padding-right: {2.5}rem;
        padding-left: {3.4}rem;
        padding-bottom: {3.4}rem;
    }} 
    </style> 
    """,
    unsafe_allow_html=True
)
st.markdown(
    """
    <style>
    MainMenu {visibility: hidden;}
    footer {visibility: hidden;}
    footer:after {
        content:"  ·  modern.millennial.market.mapping  ·  "; 
        visibility: visible;
        display: block;
        position: 'fixed';
        #background-color: red;
        padding: 5px;
        top: 2px;
    }
    </style>
    """
    , unsafe_allow_html=True
)

import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from datetime import datetime

import pages as p1
from src.tools import lists as l0
from src.tools import scripts as s0

pd.options.display.max_columns = None
pd.options.display.max_rows = None
pd.set_option("display.width", None)
pd.set_option("display.max_colwidth", -1)
pd.options.display.float_format = "{:,}".format

mpl.use("Agg")
plt.style.use("ggplot")
sm, med, lg = 10, 15, 20
plt.rc("font", size=sm)  # controls default text sizes
plt.rc("axes", titlesize=med)  # fontsize of the axes title
plt.rc("axes", labelsize=med)  # fontsize of the x & y labels
plt.rc("xtick", labelsize=sm)  # fontsize of the tick labels
plt.rc("ytick", labelsize=sm)  # fontsize of the tick labels
plt.rc("legend", fontsize=sm)  # legend fontsize
plt.rc("figure", titlesize=lg)  # fontsize of the figure title
plt.rc("axes", linewidth=2)  # linewidth of plot lines
plt.rcParams["figure.figsize"] = [18, 10]
plt.rcParams["figure.dpi"] = 150



# ------------------------------------------------------------ > page: [LOGIN_PG]


def page_login(today_stamp):
    authUser = p1.Credentials(today_stamp).check_password()
    return authUser


# ------------------------------------------------------------ > page: [HOME_PAGE]


def page_home():
    p1.Home(l0.general_pages).run_home()


# ------------------------------------------------------------ > page: [SNAPSHOT]


def page_snapshot(today_stamp):
    p1.Snapshot(today_stamp).run_mkt_snap()


# ------------------------------------------------------------ > page: [PROOF]


def page_proof():
    p1.Proof().prove_it()


# ------------------------------------------------------------ > page: [HUDDLE]


def huddle_up():
    st.header("coming soon")


# ------------------------------------------------------------ > page: [BACKTEST]


def page_backtest():
    p1.Backtest().backtest_1()


# ------------------------------------------------------------ > page: [FORECAST]


def page_forecast(today_stamp):
    p1.Forecast(today_stamp).run_forecast()


# ------------------------------------------------------------ > page: [STRATEGY]


def page_strategy(today_stamp):
    p1.Strategy(today_stamp).run_the_strats()


# ------------------------------------------------------------ > page: [ANALYSIS]


def page_analysis(today_stamp):
    p1.Analysis(today_stamp).run_analysis()


# ------------------------------------------------------------ > page: [PORTFOLIO]


def page_portfolio(today_stamp):
    p1.Portfolio(today_stamp).run_portfolio()


# ------------------------------------------------------------ > page: [RECOMMENDER]


def page_recommender(today_stamp):
    p1.Recommender(today_stamp).run_recommender()


# ------------------------------------------------------------ > page: [TEST]


def page_test_env(today_stamp, edate):
    p1.Test().run_test()
    p1.Test_Env(edate).build_test()


# ------------------------------------------------------------ > page: [RUN]



today_stamp = str(datetime.now())[:10]
# today_stamp = '2021-10-07'

if page_login(today_stamp):

    st.sidebar.title("__ · NAVIGATION · __")
    st.sidebar.markdown(f"{'__'*25} \n {'__'*25} \n")
    st.sidebar.caption(s0.navGuide_a)
    st.sidebar.caption(f"{'__'*25} \n {'__'*25} ")
    st.sidebar.caption(s0.navGuide_b)

    st.sidebar.header("__[1] Select App Section__")
    st.sidebar.caption("- __Navigate pages using the drop-down-box below__")
    systemStage = st.sidebar.radio("", l0.general_pages, key="nunya")
    st.sidebar.write(f"{'__'*25}\n {'__'*25}")


    if systemStage == "Home":
        page_home()

    if systemStage == "Market Snapshot":
        page_snapshot(today_stamp)

    if systemStage == "Investment Advisor":
        page_proof()

    if systemStage == "Asset Backtesting":
        page_backtest()

    if systemStage == "Price Forecasting":
        page_forecast(today_stamp)

    if systemStage == "Modern Strategy":
        page_strategy(today_stamp)

    if systemStage == "Portfolio Analysis":
        page_portfolio(today_stamp)

    if systemStage == "Recommender Tool":
        page_recommender(today_stamp)

    if systemStage == "Traditional Analysis":
        page_analysis(today_stamp)

    if systemStage == "Huddle-Up":
        huddle_up()

    if systemStage == "test_env":
        page_test_env()
1 Like

Thank you! That seemed to have done it for me as well!

3 Likes

Glad you were able to figure it out! I’ll also relay to our product team that this warning is perhaps not as helpful as it could be.

Best,
Randy

Hey Randy that would be great!

Again I do appreciate you reaching out on this.


I attached a screenshot of what the error looks like on the deployed app side. I think what is confusing about the language is it states the correct order is to, “called as the first Streamlit command in your script.” This doesn’t really imply to have import streamlit as st in line 1 and st.set_page_config() in line 2. If they added some language detailing that it would help those in the future!

Thanks again