Passing Credentials to Deployed Streamlit Apps using Streamlit Secrets
MUHAMMAD ABIODUN SULAIMAN
Posted on November 5, 2022
Often as programmers, we get to deal with credentials, for instance, when we need to connect to a database or ingest data from sources besides our local computers. Hence, it becomes imperative to find a way to securely pass the credentials such that they are not exposed in our code scripts.
In this short article, I will explain how I used #StreamlitSecrets to resolve a problem with passing credentials to a #MachineLearning system I deployed to the web using #Streamlit. Before fixing the problem, the deployed app worked fine on my local computer while testing it because the credentials were passed to the ingestion pipeline using an environment variable file (.env); however, upon deploying to the web, the system failed to work due to unavailability of the credentials. Some steps in solving this problem include removing the environment variable file from gitignoreand creating a Python (.py) file; since the programming language I was working with was Python. Upon taking these steps, I could not push the local repository to the remote repository as pre-commit hook detected that credentials had been exposed and did not allow the push. Hence, I finally had to use the #StreamlitSecrets file (secrets.toml) to pass the credentials while updating the credentials on the app settings section of the deployed streamlit app. The steps taken to achieve this are listed below:
- Create the directory .streamlit/
- Create the secret file secrets.toml
- In the created secret file, type in the credentials in the below format:
[db_credentials]
user = 'someuser'
password = 'somepassword'
host = 'somehost'
database = 'somedatabase'
PS: You can include other credentials as needed.
- In the python file, pass in the credentials with the following lines of code:
host=st.secrets.db_credentials.host,
user=st.secrets.db_credentials.user,
password=st.secrets.db_credentials.password,
db=st.secrets.db_credentials.database
- Navigate to the url link of the deployed app, open settings, and type in the provided credentials in .streamlit/secrets.toml
The above steps ensure that your streamlit app works seamlessly on your local computer and the Streamlit deployed version.
If you find the article helpful, kindly click the like button and comment.
Posted on November 5, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.