NelsonNN
NelsonNN

Reputation: 41

Running manage.py on Heroku for Flask app gives "could not connect"

I am trying to migrate my database on Heroku using heroku run python manage.py db migrate on my Flask app. But I am getting this error:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection 
refused
        Is the server running on host "localhost" (127.0.0.1) and accepting
        TCP/IP connections on port 5432?

Here is the code to my manage.py file:

import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import create_app, db

app=create_app()

with app.app_context():

    migrate = Migrate(app, db)
    manager = Manager(app)

    manager.add_command('db', MigrateCommand)


if __name__ == '__main__':
    manager.run()

Here is the configuration file to the database:

import os

class Config:
    SECRET_KEY= os.environ.get('SECRET_KEY')
    SQLALCHEMY_DATABASE_URI= os.environ.get('SQLALCHEMY_DATABASE_URI')
    MAIL_SERVER='smtp.googlemail.com'
    MAIL_PORT=587
    MAIL_USE_TLS = True
    MAIL_USERNAME= os.environ.get('EMAIL_USER')
    MAIL_PASSWORD= os.environ.get('EMAIL_PASS')

I have set up the sqlalchemy_database_uri to a database in PostgreSQL in this format postgres://YourUserName:YourPassword@YourHost:5432/YourDatabase. This error has been bugging me and I cannot find a solution anywhere.

Why isn't this working?

Upvotes: 0

Views: 190

Answers (1)

Chris
Chris

Reputation: 136958

You can't connect your Heroku application to your local database without some major drawbacks. It's a huge pain to set up (you'll need to deal with port forwarding and likely at least one firewall, probably dynamic IP addresses, ...) and your application won't run if your laptop is off.

A better solution would be to have a database in the cloud, and given that you are already using Heroku and PostgreSQL the most natural choice is Heroku's own Postgres service. If you're depending on psycopg2, there's a good chance that one has already been provisioned for you.

If it has, you'll see a DATABASE_URL environment variable containing your connection string. Simply set your SQLAlchemy database URI from that:

SQLALCHEMY_DATABASE_URI= os.environ.get('DATABASE_URL')

If a database hasn't been provisioned for you (check by running heroku addons) you can provision one using the free tier easily:

heroku addons:create heroku-postgresql:hobby-dev

Note that you shouldn't be running manage.py db migrate on Heroku at all. This generates migration files, which will be lost on Heroku's ephemeral filesystem. Generate migrations locally, and commit the migration files. You'll want to run manage.py db upgrade in both places, though.

Upvotes: 1

Related Questions