Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def main():
|
| 2 |
+
st.title("🤗 Streamlit App with Secrets")
|
| 3 |
+
st.write("This application demonstrates how to access secret API keys securely on Hugging Face Spaces.")
|
| 4 |
+
|
| 5 |
+
# Accessing secrets
|
| 6 |
+
# On Hugging Face Spaces, go to 'Settings' > 'Variables and secrets' to add your key.
|
| 7 |
+
# In Streamlit, these are accessible via st.secrets
|
| 8 |
+
|
| 9 |
+
SECRET_KEY_NAME = "MY_API_KEY"
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
# Check if the key exists in secrets
|
| 13 |
+
if SECRET_KEY_NAME in st.secrets:
|
| 14 |
+
api_key = st.secrets[SECRET_KEY_NAME]
|
| 15 |
+
|
| 16 |
+
st.success(f"Successfully loaded secret: `{SECRET_KEY_NAME}`")
|
| 17 |
+
|
| 18 |
+
# Display a masked version of the key for verification (NEVER print the full key in a real app)
|
| 19 |
+
masked_key = f"{api_key[:4]}{'*' * (len(api_key) - 4)}" if len(api_key) > 4 else "****"
|
| 20 |
+
st.code(f"Key Value: {masked_key}", language="text")
|
| 21 |
+
|
| 22 |
+
st.info("You can now use this variable `api_key` to make authenticated requests.")
|
| 23 |
+
|
| 24 |
+
else:
|
| 25 |
+
st.warning(f"Secret `{SECRET_KEY_NAME}` not found.")
|
| 26 |
+
st.markdown("""
|
| 27 |
+
**How to fix:**
|
| 28 |
+
1. Go to your Hugging Face Space **Settings**.
|
| 29 |
+
2. Scroll to **Variables and secrets**.
|
| 30 |
+
3. Click **New secret**.
|
| 31 |
+
4. Name: `MY_API_KEY`.
|
| 32 |
+
5. Value: *Your actual API key*.
|
| 33 |
+
""")
|
| 34 |
+
|
| 35 |
+
except FileNotFoundError:
|
| 36 |
+
# This handles local development if .streamlit/secrets.toml is missing
|
| 37 |
+
st.error("Secrets configuration not found.")
|
| 38 |
+
st.markdown("If running locally, ensure you have a `.streamlit/secrets.toml` file.")
|
| 39 |
+
|
| 40 |
+
if __name__ == "__main__":
|
| 41 |
+
main()
|