'How to set and access environment variables in python file for Streamlit app?

How do you properly set secret keys or environment variables when you deploy your files to github to be deploy to Streamlit app?



Solution 1:[1]

Streamlit has an option in the advanced settings before you deploy your application to store your secret keys and environment variables

enter image description here

And inside your app, you can just query the variables as below:

import streamlit as st

# Everything is accessible via the st.secrets dict:

st.write("DB username:", st.secrets["db_username"])
st.write("DB password:", st.secrets["db_password"])
st.write("My cool secrets:", st.secrets["my_cool_secrets"]["things_i_like"])

# And the root-level secrets are also accessible as environment variables:

import os

st.write(
    "Has environment variables been set:",
    os.environ["db_username"] == st.secrets["db_username"],
)

Source: https://docs.streamlit.io/streamlit-cloud/get-started/deploy-an-app/connect-to-data-sources/secrets-management

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mightyandweakcoder