<aside> ⚠️ DEPRECATED!!! This guide migrated to our docs. Please view the current version at: https://docs.streamlit.io/en/stable/tutorial/postgresql.html
</aside>
This guide explains how to securely access a PostgreSQL database from Streamlit sharing or Streamlit for Teams. It uses the psycopg2 library and Streamlit's secrets management (requires streamlit v0.80.0 or higher).
<aside> 🏃 If you already have a database that you want to use, feel free to skip this step.
</aside>
First, follow this tutorial to install PostgreSQL and create a database (note down the database name, username, and password!). Open the SQL Shell (psql
) and enter the following two commands to create a table with some example values:
CREATE TABLE mytable (
name varchar(80),
pet varchar(80)
);
INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird');
Your local Streamlit app will read secrets from a file .streamlit/secrets.toml
in your app's root dir. Create this file if it doesn't exist yet and add the name, user, and password of your database as shown below:
# .streamlit/secrets.toml
[postgres]
host = "localhost"
port = 5432
dbname = "xxx"
user = "xxx"
password = "xxx"
<aside>
☝ Add this file to .gitignore
and don't commit it to your Github repo!
</aside>
As the secrets.toml
file above is not commited to Github, you need to pass its content to your deployed app (on Streamlit sharing or Streamlit for Teams) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets. Copy the content of secrets.toml
into the text area. More infos in Secrets Management.
pip install psycopg2-binary
Add the package to your requirements.txt
file, preferably pinning its version (just replace x.x.x
with the version you installed):
# requirements.txt
psycopg2-binary==x.x.x