could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host and accepting TCP/IP connections on port 5432? code example

Example 1: could not connect to server: Connection refused Is the server running on host and accepting TCP/IP connections on port 5432?

cd /etc/postgresql/9.x/main/
------- open file named postgresql.conf
sudo nano postgresql.conf
------- add this line to that file
listen_addresses = '*'
------- then open file named pg_hba.conf
sudo nano pg_hba.conf
------- and add this line to that file
host  all  all 0.0.0.0/0 md5
------- restart your server
sudo /etc/init.d/postgresql restart

Example 2: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?

# It happend because you are not running 
service postgresql status # to check the status of database
# if it's Active: inactive the you are getting this error.
# to over ride this error you should up and run server
service postgresql start