<aside> ⚠️ DEPRECATED!!! This guide migrated to our docs. Please view the current version at: https://docs.streamlit.io/en/stable/tutorial/postgresql.html

</aside>

Introduction

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).

Step 1: Create a PostgreSQL database

<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');

Step 2: Add username and password to your local app secrets

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>

Step 3: Copy your app secrets to the cloud

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.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/24e1199d-f19e-40c6-b4f5-c0f4598556de/Screenshot_2021-05-04_at_19.01.58.png

Step 4: Install psycopg2 and add it to your requirements file

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