Unable to connect to Heroku postgre SQL database locally
<p>I am trying to connect to Heroku postgre SQL database locally like this,</p>

<pre><code>from flask import Flask
import sys
import psycopg2
import urlparse

urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse("postgres://url")

conn = psycopg2.connect(
    database=url.path[1:],
    user=url.username,
    password=url.password,
    host=url.hostname,
    port=url.port
)
</code></pre>

<p>But after a lengthy pause I get the following error, </p>

<pre><code>psycopg2.OperationalError: could not connect to server: Connection timed out
    Is the server running on host "URL" (IP) and accepting
    TCP/IP connections on port 5432?
</code></pre>

<p>How can I fix this error and connect to the database locally?</p>

<p>Kinda tough for me to narrow down, but I was able to set something similar with these steps:</p>

<p>If you have a 'server.py' make sure to have this at the top of the file:</p>

<pre><code>from dotenv import load_dotenv, find_dotenv
import os

load_dotenv(find_dotenv())
db = pg.DB(
  dbname=os.environ.get('DBNAME'),
  host=os.environ.get('DBHOST'),
  port=int(os.environ.get('DBPORT')),
  user=os.environ.get('DBUSER'),
  passwd=os.environ.get('DBPASSWORD')
)
</code></pre>

<p>Dump the following in a Procfile (spell Procfile exactly like that)</p>

<pre><code>web: gunicorn -b 0.0.0.0:$PORT -w 4 server:app
</code></pre>

<p>Lastly, you need a requirements.txt that lists all Python modules you have installed. You can do this with the command: pip freeze > requirements.txt</p>

<p>Hope that helps.</p>

python postgresql heroku