Error when deploying my streamlit app

Can anyone tell me why I get this error after deploying my app on streamlit-cloud?
It works fine on localhost but after deployment I get a NameError. The log says the following:

2023-08-16 19:38:49.774 Uncaught app exception
Traceback (most recent call last):
  File "/home/adminuser/venv/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 552, in _run_script
    exec(code, module.__dict__)
  File "/mount/src/streamlit_my_info/pages/04 Notes and Links.py", line 58, in <module>
    for m in filesNfolders:
NameError: name 'filesNfolders' is not defined

The code of 04 Notes and Links.py is:

import re
import sys
import os
import requests
import streamlit as st
import pandas as pd

# appending the directory of GetGitInfo.py in the sys.path list
GIT_INFO = os.path.dirname(os.path.abspath('./modules/GetGitInfo.py'))
PAGE_SETUP = os.path.dirname(os.path.abspath('./modules/PageSetup.py'))
HTTP_SETUP = os.path.dirname(os.path.abspath('./modules/StatusCodes.py'))
sys.path.insert(1, GIT_INFO)
sys.path.insert(1, PAGE_SETUP)
sys.path.insert(1, HTTP_SETUP)

import PageSetup as PS
import GetGitInfo as GGI
import StatusCodes as HS  
 
path_to_clone = 'clone/WEB_LINKS'
github_name = 'WEB_LINKS'


paSep = os.path.sep
# print(paSep)
try:
    start_folders = GGI.get_root_folders(
        f'{os.path.dirname(__file__)}{paSep}..{paSep}{path_to_clone}')

    project_root = GGI.get_project_root()
except FileNotFoundError:
    start_folders = []
    project_root = []
    url = []
    filesNfolders = []
    st.session_state.filesNfolders
    st.write(f'{github_name} could not be found or has not been cloned')

select_names = []
fi_dir_name = []
url_setup = []
index = 0

index = 80
for n in start_folders:
    filesNfolders = GGI.get_folders_files(os.path.abspath(
    f"{project_root}{paSep}{path_to_clone}"), paSep)


root_length = len(f'{project_root}{paSep}{path_to_clone}')+1

for m in filesNfolders:
    file_name = m[root_length:]
    file_name = file_name[:-3]
    file_exclude = [f'{paSep}__']
    excluded = re.search(file_exclude[0], file_name)
    # print(excluded)
    if not file_name[0] == '.' and excluded == None:
        url_setup.append({'name': file_name, "url": m})
        select_names.append(file_name)


option = st.selectbox("**Select category**", (select_names))

# st.write('---')

for sub in url_setup:
    if sub['name'] == option:
        url = sub['url']
        page = sub['name']

filename = ''
try:
    with open(f"{url}", 'r', encoding='utf-8') as file:
        data = file.read()
        # st.write(filesNfolders[index])
        st.write(data)
except FileNotFoundError:
    if not url == []:
        msg = "Sorry, the file " + filename + " does not exist."
        print(msg)
        st.write(msg)


link_name = "[^\[]+"
link_url = "http[s]?://.+"
markup_regex = f'\[({link_name})]\(\s*({link_url})\s*\)'

st.write('')
st.write('')
st.write('---')
# st.write('')

links_urls = []

try:
    if st.button('Show links'):
        with st.spinner(f'**LOADING** &nbsp; &nbsp; It might take a while. &nbsp; &nbsp; Please wait... '):
            with open(f'{url}', 'r',  encoding='utf-8') as file:
                for line in file:
                    web_urls = re.findall(markup_regex, line)
                    if web_urls:
                        status = requests.get(web_urls[0][1]).status_code
                        status_txt = HS.get_http_status_code(status)
                        # if status < 200 or status >= 300:
                        links_urls.append({#"page": page,
                                            #"Title": web_urls[0][0],
                                            "URL": f'{web_urls[0][1]}',
                                            #"Status": status,
                                            "Status": status_txt
                                            })
    if not len(links_urls) == 0:
        st.write('##### **Page links**')
        df = pd.DataFrame(links_urls)
        st.markdown(df.to_html(render_links=True, index=False),unsafe_allow_html=True)
        # st.table(df)
except requests.exceptions.ConnectionError:
    msg = "Sorry, there was an Connection Error. Please try again."
    print(msg)
    st.write(msg)
except FileNotFoundError:
    st.write('There is no links to be found!')

It is saying the name filesNfolders is not defined
so its not in that scope to access it
so define it globally and try again?

I have tried that already. But I keep getting errors. The wired thing is it works on local hostโ€ฆ

Hi,

The problem is actually occurring because your start_folders list is empty. Due to this, in this part of the code:

for n in start_folders:
    filesNfolders = GGI.get_folders_files(os.path.abspath(
    f"{project_root}{paSep}{path_to_clone}"), paSep)

The for loop does not run since there is nothing actually present to iterate over in start_folders (empty list). So, the assignment line with filesNfolders does not get executed.

The problem seems to be here:

start_folders = GGI.get_root_folders(
        f'{os.path.dirname(__file__)}{paSep}..{paSep}{path_to_clone}')

There is probably FileNotFound error occurring here, which is causing the except block to trigger, making the start_folders list empty:

except FileNotFoundError:
    start_folders = []

Iโ€™m not sure what this line does, but if you can just give a little context about this line:
start_folders = GGI.get_root_folders(
fโ€™{os.path.dirname(file)}{paSep}โ€ฆ{paSep}{path_to_clone}')

then we might be able to help you about this error. According to my observation, you might be trying to traverse the Streamlit serverโ€™s directory from the root, which is why the FileNotFound error occurs.

Cheers,
Moiz

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.