Streamlit - 访问 Google 云端硬盘

问题描述 投票:0回答:1

感谢您阅读本文。我正在尝试构建 Streamlit 应用程序,并且希望能够连接到 Google Drive 并在 Streamlit 应用程序中检索我的云端硬盘中的一些文件。

在我的本地计算机上,我可以运行以下几行来执行此操作:

auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)



#Download files in sheet names
drive_service = build('drive', 'v3', credentials=gauth.credentials)
for file_name in sheet_names:
  file = drive.ListFile({ "q":"title='example",includeItemsFromAllDrives":"True",supportsAllDrives":"True", "corpora":"allDrives"}).GetList()

上面的代码将登录并从我的 Google 云端硬盘下载一个名为 example 的文件。我想在 Streamlit 中重现这一点。不幸的是,我无法像在本地计算机上那样登录,据我所知,我应该使用服务帐户。如果您可以与我分享一些代码,那就太好了。

谢谢!

python google-drive-api streamlit drive
1个回答
0
投票

我也尝试过设置和使用 oauth2 用户凭据,并且尝试过服务帐户,在这两种情况下我都得到一个空白列表。我也尝试过drive.mount,但是如果您在与streamlit相同的单元中执行此操作,它将无法进行身份验证。所以在所有情况下我的文件夹列表都是空的...

def authenticate_gdrive():
   gauth = GoogleAuth()
   # Load client secrets from the provided path.
   gauth.LoadClientConfigFile(auth_user_credentials_path)

   # Use the following line for authentication in Google Colab
   gauth.CommandLineAuth()

   return GoogleDrive(gauth)

我还尝试过设置和使用服务帐户。

def get_drive_service():
    creds = None
    st.write(f'google_credentials_path = {google_credentials_path}')

    if google_credentials_path:
        creds =     service_account.Credentials.from_service_account_file(google_credentials_path)
        st.write(f"Credentials = {creds}")
        st.write(f'Credentials expired: {creds.expired}')

    else:
        st.warning("Credentials path not found in environment variables.")
        return None

    service = build('drive', 'v3', credentials=creds)
    return service

我想要做的就是将与我的 Streamlit 应用程序的交互历史记录保存在 Word 文档中。因此,我只希望以下内容能够工作,但唯一有效的调试语句是调试驱动器路径,因为驱动器路径是硬编码的。调试文件夹没有显示,因为 os.walk 没有响应。

    with st.sidebar:

        st.sidebar.header("Select Save Folder")
        # Define the path to your Google Drive
        drive_path = '/content/drive/My Drive'
        st.write(f"Debug drive path - {drive_path}")

        # List the subdirectories in your Google Drive
        #folders = [d for d in os.listdir(drive_path) if os.path.isdir(os.path.join(drive_path, d))]

        # Using os.walk to list directories
        folders = next(os.walk(drive_path))[1]
        st.write(f"Debug folders - {folders}")  # Debug statement to print the folders list
        

        if folders:
            selected_folder_name = st.selectbox('Select folder:', folders, index=0)
            selected_folder_path = os.path.join(drive_path, selected_folder_name)
        else:
            st.error('No folders found.')

    if st.button('Save Conversation to Word',key='save_button_outside_function'):
            save_conversation_to_word(st.session_state.chat_history)
© www.soinside.com 2019 - 2024. All rights reserved.