warnerm06
warnerm06

Reputation: 814

Flask App AWS Postgres Connection Works Locally but Not on Heroku

MY Flask App AWS Postgres connection works locally but not on Heroku. The app works on Heroku but it does not get/send data to AWS Postgres.

Heroku logs point to a problem in which the endpoint is in double double quotes. I'm uncertain of how to troubleshoot this as I'm using SQLAlchemy which uses psycopg2. I'm not using psycopg2 directly.

My AWS security group is set to all inbound IPs.

Changed AWS to accept all inbound IPs. Googled until all links are purple. Hard to search for "double double quotes" and get a good result.

Error from Heroku Logs: host name is in double double quotes which may be the problem

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not 
translate host name ""xxxx.xxxx.us-east- 
2.rds.amazonaws.com"" to address: Name or service not known

My Environment Variable for DB_URI:

'postgres://username:password@awsdbname.*******.us-east- 
2.rds.amazonaws.com/dbname'

AWS Security

PostgreSQL TCP 5432 0.0.0.0/0 Anywhere-Delete
PostgreSQL TCP 5432 ::/0      Anywhere-Delete
I will change this when in production.

Edit: Connection code:

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(Config)

    db.init_app(app)

class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY')
    # SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URI')
    SQLALCHEMY_DATABASE_URI = f"postgres://{os.environ.get('AWS_DB_USER')}:{os.environ.get('AWS_DB_PASS')}@{os.environ.get('AWS_DB_ENDPOINT')}/mydb"

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)

Running the exact same code works locally. My DB is readable/writable.Running on Heroku my app loads but doesn't read/write to Postgres. This points to a permissions issue but I've allowed all inbound traffic on AWS. Any help would be appreciated. Not sure why psycopg2 would parse correctly locally but not on Heroku.

Upvotes: 1

Views: 394

Answers (1)

warnerm06
warnerm06

Reputation: 814

Solution: Change DB_URI config variable in Heroku. I removed the quotes around my environment variable in Heroku. This is still strange as some posts suggest quotes are required for Heroku Config Variables. I still don't know why it works locally but not in production. Hope this helps someone else.

Upvotes: 1

Related Questions