Spaces:
Sleeping
Sleeping
Download db.py from AimanGh/explore_Chinese: direct link, hf CLI and curl.
- Browser
- Download file 1.15 kB
-
https://huggingface.co/spaces/AimanGh/explore_Chinese/resolve/main/db.py
- Command line
-
hf download hf://spaces/AimanGh/explore_Chinese/db.py
-
curl -L -o db.py https://huggingface.co/spaces/AimanGh/explore_Chinese/resolve/main/db.py
1.15 kB
| # db.py | |
| import os | |
| import pandas as pd | |
| from sqlalchemy import create_engine | |
| import streamlit as st | |
| def _get_conn_str(): | |
| # HF Spaces: secrets/variables are environment vars | |
| for key in ("DB_CONNECTION", "DATABASE_URL", "db_connection", "database_url"): | |
| val = os.environ.get(key) | |
| if val: | |
| return val | |
| # Streamlit Cloud/local: secrets.toml | |
| try: | |
| for key in ("db_connection", "DATABASE_URL", "database_url"): | |
| if key in st.secrets: | |
| return st.secrets[key] | |
| except Exception: | |
| pass | |
| return None | |
| CONN_STR = _get_conn_str() | |
| engine = create_engine(CONN_STR, pool_pre_ping=True) if CONN_STR else None | |
| def run_query(query: str) -> pd.DataFrame: | |
| if engine is None: | |
| st.error( | |
| "No database connection configured. " | |
| "Set DB_CONNECTION in your HF Space (Settings → Variables & secrets) " | |
| "or add db_connection to .streamlit/secrets.toml." | |
| ) | |
| return pd.DataFrame() | |
| with engine.connect() as conn: | |
| # use read_sql_query to be explicit; no trailing comma! | |
| return pd.read_sql_query(query, conn) | |