I am trying to create a multipage application -

The sections are opening on the web browser but none of the content of the python file is loading and it is not even showing any error

import streamlit as st

Define pages with titles and icons

login_page = st.Page(“account/login.py”, title=“Log in”, icon=“:material/login:”, default=True)

dashboard_page = st.Page(“mainmenu/dashboard.py”, title=“Dashboard”, icon=“:material/dashboard:”)
home_page = st.Page(“mainmenu/home.py”, title=“Home”, icon=“:material/home:”)

word_to_pdf_page = st.Page(“convertfiles/word_to_pdf.py”, title=“Word to PDF”, icon=“:material/description:”)
png_to_pdf_page = st.Page(“convertfiles/png_to_pdf.py”, title=“PNG to PDF”, icon=“:material/description:”)
jpg_to_pdf_page = st.Page(“convertfiles/jpg_to_pdf.py”, title=“JPG to PDF”, icon=“:material/description:”)
excel_to_pdf_page = st.Page(“convertfiles/excel_to_pdf.py”, title=“Excel to PDF”, icon=“:material/picture_as_pdf:”)
pdf_to_jpg_page = st.Page(“convertfiles/pdf_to_jpg.py”, title=“PDF to JPG”, icon=“:material/picture_as_pdf:”)

merge_pdf_page = st.Page(“pdfop/merge_pdf.py”, title=“Merge PDFs”, icon=“:material/merge_type:”)
protect_pdf_page = st.Page(“pdfop/protect_pdf.py”, title=“Protect PDF”, icon=“:material/lock:”)
unlock_pdf_page = st.Page(“pdfop/unlock_pdf.py”, title=“Unlock PDF”, icon=“:material/lock_open:”)
organise_pdf_page = st.Page(“pdfop/organise_pdf.py”, title=“Organise PDF”, icon=“:material/folder:”)
split_pdf_page = st.Page(“pdfop/split_pdf.py”, title=“Split PDF”, icon=“:material/vertical_split:”)
extract_pdf_page = st.Page(“pdfop/extract_pdf.py”, title=“Extract PDF”, icon=“:material/filter_frames:”)
compress_pdf_page = st.Page(“pdfop/compress_pdf.py”, title=“Compress PDF”, icon=“:material/compress:”)

Initialize session state for authentication status

if ‘authenticated’ not in st.session_state:
st.session_state.authenticated = False

Set up navigation with sections and pages

if st.session_state.authenticated:
pg = st.navigation(
{
“Account”: [login_page],
“Main Menu”: [home_page, dashboard_page],
“Convert Files”: [word_to_pdf_page, jpg_to_pdf_page, png_to_pdf_page, pdf_to_jpg_page, excel_to_pdf_page],
“PDF Operations”: [merge_pdf_page, protect_pdf_page, unlock_pdf_page, organise_pdf_page, split_pdf_page, extract_pdf_page, compress_pdf_page]
}
)
else:
pg = st.navigation([login_page])

Set the Powergrid logo

st.logo(“Images/powergrid.webp”)

Run the navigation

pg.run()

Please Help!


Only the login page works because it is set as default , no other page is loading

Hi @Ravi2,

Please can you edit your post so your code is formatted in a block and readable?

Since you show a screenshot with the menu for your logged-in state, that should mean Streamlit sees the referenced files.

Just focusing on one page as an example, what is the URL when you click on the your dashboard_page? Can you try manually setting url_path="dashboard" to see if that changes anything?

import streamlit as st


# Define pages with titles and icons
login_page = st.Page("account/login.py", title="Log in", icon=":material/login:", default=True)

dashboard_page = st.Page("mainmenu/dashboard.py", title="Dashboard", icon=":material/dashboard:")
home_page = st.Page("mainmenu/home.py", title="Home", icon=":material/home:")

word_to_pdf_page = st.Page("convertfiles/word_to_pdf.py", title="Word to PDF", icon=":material/description:")
png_to_pdf_page = st.Page("convertfiles/png_to_pdf.py", title="PNG to PDF", icon=":material/description:")
jpg_to_pdf_page = st.Page("convertfiles/jpg_to_pdf.py", title="JPG to PDF", icon=":material/description:")
excel_to_pdf_page = st.Page("convertfiles/excel_to_pdf.py", title="Excel to PDF", icon=":material/picture_as_pdf:")
pdf_to_jpg_page = st.Page("convertfiles/pdf_to_jpg.py", title="PDF to JPG", icon=":material/picture_as_pdf:")

merge_pdf_page = st.Page("pdfop/merge_pdf.py", title="Merge PDFs", icon=":material/merge_type:")
protect_pdf_page = st.Page("pdfop/protect_pdf.py", title="Protect PDF", icon=":material/lock:")
unlock_pdf_page = st.Page("pdfop/unlock_pdf.py", title="Unlock PDF", icon=":material/lock_open:")
organise_pdf_page = st.Page("pdfop/organise_pdf.py", title="Organise PDF", icon=":material/folder:")
split_pdf_page = st.Page("pdfop/split_pdf.py", title="Split PDF", icon=":material/vertical_split:")
extract_pdf_page = st.Page("pdfop/extract_pdf.py", title="Extract PDF", icon=":material/filter_frames:")
compress_pdf_page = st.Page("pdfop/compress_pdf.py", title="Compress PDF", icon=":material/compress:")

# Initialize session state for authentication status
if 'authenticated' not in st.session_state:
    st.session_state.authenticated = False

# Set up navigation with sections and pages
if st.session_state.authenticated:
    pg = st.navigation(
        {
            "Account": [login_page],
            "Main Menu": [home_page, dashboard_page],
            "Convert Files": [word_to_pdf_page, jpg_to_pdf_page, png_to_pdf_page, pdf_to_jpg_page, excel_to_pdf_page],
            "PDF Operations": [merge_pdf_page, protect_pdf_page, unlock_pdf_page, organise_pdf_page, split_pdf_page, extract_pdf_page, compress_pdf_page]
        }
    )
else:
    pg = st.navigation([login_page])

# Set the Powergrid logo
st.logo("Images/powergrid.webp")

# Run the navigation
pg.run()```

Screenshot 2024-07-16 115225
This is the folder structure.

http://localhost:8502/dashboard This is the url of the dashboard and i tried using the method you suggested

dashboard_page = st.Page("mainmenu/dashboard.py", title="Dashboard", icon=":material/dashboard:", url_path="dashboard")

and it did not work either , This application works properly as long as i use the traditional method of making multipage application that is storing all the files in the “pages” folder and using Login.py as the main file but when i tried to add sections to the side bar the problems occurs

Can you share the code contents of one of your pages?

import streamlit as st
from docx2pdf import convert
import tempfile
import os
import pythoncom
import datetime
import pyodbc
import socket

# Function to connect to the database
def connect_to_db():
    conn = pyodbc.connect(
        "Driver={ODBC Driver 18 for SQL Server};"
        "Server=Z3PR\\SQLEXPRESS;"
        "Database=PowergridDB;"
        "UID=sa;"
        "PWD=password230;"
        "Encrypt=no;"
    )
    return conn

st.logo("Images/powergrid.webp")


# Function to insert file data using a stored procedure
def insert_file_data(name, description, status, content_type, size, updated_by, updated_on, updated_from):
    try:
        conn = connect_to_db()
        if conn:
            cursor = conn.cursor()

            # Convert Python types to SQL Server expected types
            updated_on_sql = updated_on.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] if isinstance(updated_on, datetime.datetime) else updated_on
            size = int(size)  # Convert size to integer
            status = int(status)  # Convert status to integer

            # Call the stored procedure with parameters in correct order
            cursor.execute("{CALL sp_InsertFile ( ?, ?, ?, ?, ?, ?, ?, ?)}",
                           (name, description, status, content_type, size, updated_by, updated_on_sql, updated_from))

            conn.commit()
            # st.info("File logged successfully!")
    except pyodbc.Error as e:
        st.error(f"Error inserting file data: {e}")
        # More detailed error logging
        st.write("SQL Error:", e)
        st.write("SQL State:", e.args[0])
        st.write("SQL Message:", e.args[1])
    except Exception as ex:
        st.error(f"Unexpected error: {ex}")
    finally:
        if conn:
            conn.close()


# Main Streamlit application function
def app():
    st.set_page_config(
        page_title="निर्मल: DOCX to PDF",
        page_icon="🔄",
        layout="centered",
        initial_sidebar_state="expanded"
    )

    st.markdown(
        """
        <style>
            [data-testid=stSidebar] [data-testid=stImage]{
                text-align: center;
                display: block;
                margin-left: auto;
                margin-right: auto;
                width: 100%;
            }
        </style>
        """, unsafe_allow_html=True
    )

    with st.sidebar:
        st.image('./Images/logo-white.png', width=150)

    with st.sidebar:
        st.markdown(f"""<h6 style='text-align: center;'>Powergrid &copy; {datetime.datetime.now().year} All rights reserved.</h6>""", unsafe_allow_html=True)

    if not st.session_state.authenticated:
        st.error(" 🔒 Please log in before accessing the resource.")
        return

    pythoncom.CoInitialize()

    st.markdown("<h1 style='text-align: center;'><  निर्मल: DOC To PDF Converter  ></h1>", unsafe_allow_html=True)
    st.image('./Images/word-to-pdf-color.webp', width=600)

    uploaded_file = st.file_uploader("*Upload a Word file that you want to convert.", type="docx", key="docx_uploader")

    if uploaded_file is not None:
        docx_magic_number = b"\x50\x4B\x03\x04"  # Magic number for DOCX files
        first_bytes = uploaded_file.read(len(docx_magic_number))
        uploaded_file.seek(0)

        if first_bytes == docx_magic_number:
            st.success("Word Document uploaded successfully!")

            file_size = len(uploaded_file.getvalue())

            with tempfile.NamedTemporaryFile(delete=False, suffix=".docx") as temp_docx:
                temp_docx.write(uploaded_file.read())
                temp_docx_path = temp_docx.name

            with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
                temp_pdf_path = temp_pdf.name

            convert(temp_docx_path, temp_pdf_path)

            with open(temp_pdf_path, "rb") as f:
                st.download_button(
                    label="Download PDF",
                    data=f,
                    file_name="converted.pdf",
                    mime="application/pdf"
                )

            os.remove(temp_docx_path)
            os.remove(temp_pdf_path)
        else:
            st.error("Please upload a valid DOCX file.")

        
        insert_file_data(
                name=uploaded_file.name,
                description = "Word to PDF",
                status=1,  # Example status
                content_type=os.path.splitext(uploaded_file.name)[1].lower(),  # Get file extension
                size=file_size,
                updated_by= st.session_state.username ,  # Get current user's login name
                updated_on=datetime.datetime.now(),  # Current date and time
                updated_from=socket.gethostbyname(socket.gethostname())  # Example of retrieving hostname
            )


    pythoncom.CoUninitialize()

if __name__ == "__main__":
    app()

The code i shared with you is the code for word to pdf conversion page.

This is the problem. __name__=="__main__" only for the entrypoint file.

You should treat your pages as pure scripts. If you really, truly need the __name__ test, then it should be "__page__".

This was just updated in docs and will show up in the next version:

A page can be defined by a Python file or Callable. Python files used as a StreamlitPage source will have __name__ == "__page__". Functions used as a StreamlitPage source will have __name__ corresponding to the module they were imported from. Only the entrypoint file and functions defined within the entrypoint file have __name__ == "__main__" to adhere to Python convention.

2 Likes

It works perfectly now! Thanks a lot , It has been few days since i was stuck with this. This helped me a lot.

1 Like