How to use secrets in streamlit app safely


When using streamlit app, how to manage secrets? It is quite easy to use st.secrets function.

when running your Streamlit app locally, you can store secrets in a .streamlit/secrets.toml file. Streamlit uses TOML (Tom’s Obvious, Minimal Language) format for the secrets file, not YAML. Here’s how you can set it up:

Step 1: Create the Secrets File

Create a file named secrets.toml inside a .streamlit folder at the root of your project directory. Your project structure should look something like this:

your_project/
├─ .streamlit/
│ ├─ secrets.toml
├─ your_script.py
├─ other_files

Step 2: Add Your Secrets to the File

In secrets.toml, you can add your secrets like this:

# .streamlit/secrets.toml
my_api_key = "your-secret-api-key"

Step 3: Access the Secrets in Your Streamlit App

In your Streamlit script (your_script.py), you can access these secrets using st.secrets. For example:

import streamlit as st

# Access the secret
api_key = st.secrets["my_api_key"]

# Rest of your Streamlit code

for example, if we have a html code to render, we can use the secrets this way:

import streamlit as st

# Access the secret
api_key = st.secrets["my_api_key"]

html_content = f"""
<html>
<head>
<script>
var apiKey = '{api_key}';
console.log('API Key:', apiKey); // This line will log the API key to the browser's console
// Your JavaScript code
</script>
</head>
<body>
<!-- Your HTML content -->
</body>
</html>
"""
print(html_content) # Debug: Check if the API key is correctly injected
st.components.v1.html(html_content, height=600)



Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC