Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psycopg2.OperationalError: could not connect to server: Connection refused

import os
import datetime
from flask import Flask, render_template, redirect, url_for
#from database import DatabaseConnection
#from models import kayıt
from forms import LoginForm
import psycopg2 as p

conn=p.connect(dbname='app_db', user='postgres', host='localhost', password='samet', port=5432)
conn.autocommit=True
cur=conn.cursor()   

conn'and line

psycopg2.OperationalError: could not connect to server: Connection refused

use; postgresql:9.6.5 python:3

If I only run postgre with the info, but it is not running in python

thank you

Sorry, I should have explained a little more clearly. I'm dealing with a docker. And I have 3 containers, but I am trying to use python container via PostgreSQL. I want to use psycopg2 for this. But I am getting such an error. My login information is correct. I checked.

like image 613
samet yılmaz Avatar asked Oct 16 '22 19:10

samet yılmaz


2 Answers

Figure out how to solve this problem :

according to this answer:

Postgres is not running in the same container as the flask application, that why it cannot be acceded via localhost. we should find the IP address of the docker container with flask and add it, or just add Postgres or volume_name in place of localhost.

So your connection should be like this :

conn=p.connect(dbname='app_db', user='postgres', host='volume_name_of_postgres_in_docker_compose', password='samet', port=543
like image 82
Espoir Murhabazi Avatar answered Oct 19 '22 11:10

Espoir Murhabazi


Are you sure all the arguments you are passing to the psycopg2 connect function are correct?

conn=p.connect(dbname='app_db', user='postgres', host='localhost', password='samet', port=5432)

The database name, username, host, password, and port all could possibly be incorrect.

like image 25
RealPawPaw Avatar answered Oct 19 '22 12:10

RealPawPaw