Search code examples
postgresqlherokuheroku-postgresheroku-cli

How can I access to a PostgreSQL DB from outside of a heroku app (for a Python app)


I have a PostgreSQL DB hosted in heroku and I want to get access from other applications which aren't hosted in heroku, but I saw in the DB settings that the credentials are not permanent.

How can I get access from other application always having updated credentials?


Solution

  • Heroku recommends using the Heroku CLI to fetch fresh credentials every time you run your external application:

    Always fetch the database URL config var from the corresponding Heroku app when your application starts. For example, you may follow 12Factor application configuration principles by using the Heroku CLI and invoke your process like so:

    DATABASE_URL=$(heroku config:get DATABASE_URL -a your-app) your_process
    

    This way, you ensure your process or application always has correct database credentials.

    In this example, your_process will see an environment variable called DATABASE_URL that is set to the same value as the DATABASE_URL config far on the Heroku app called your-app.

    Since you are using Python, here is one way to access that value:

    import os
    
    
    database_url = os.getenv("DATABASE_URL", default="some_default_for_local_development")