django.db.utils.OperationalError Could not connect to server - python

I am not sure how to fix this issue
I have no idea why I am getting this error when I try to runserver:
Performing system checks...
System check identified no issues (0 silenced).
Unhandled exception in thread started by <function wrapper at 0x1085589b0>
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 222, in wrapper
fn(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run
self.check_migrations()
File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 159, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "/Library/Python/2.7/site-packages/django/db/migrations/executor.py", line 17, in __init__
self.loader = MigrationLoader(self.connection)
File "/Library/Python/2.7/site-packages/django/db/migrations/loader.py", line 49, in __init__
self.build_graph()
File "/Library/Python/2.7/site-packages/django/db/migrations/loader.py", line 184, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/Library/Python/2.7/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations
self.ensure_schema()
File "/Library/Python/2.7/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema
if self.Migration._meta.db_table in self.connection.introspection.get_table_list(self.connection.cursor()):
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 165, in cursor
cursor = self.make_debug_cursor(self._cursor())
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 138, in _cursor
self.ensure_connection()
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 133, in ensure_connection
self.connect()
File "/Library/Python/2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 133, in ensure_connection
self.connect()
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 122, in connect
self.connection = self.get_new_connection(conn_params)
File "/Library/Python/2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 134, in get_new_connection
return Database.connect(**conn_params)
File "/Library/Python/2.7/site-packages/psycopg2/__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
django.db.utils.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?
When I try to connect to postgres:
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'beerad',
'USER': 'bli1',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}

It can be some issues:
PostgreSQL is not running. Check it with sudo service postgresql status
Your PostgresSQl is not running on port 5432. You can check it typing sudo netstat -nl | grep postgres
You have something wrong trying to connect to your db like the username, the password or the databasename. Check that they are what postgres ask for you to connect it and that is the db_name that you want to access to.
Problems with postmaster.pid in postgres. It can happen because of a shutdown unproperly done. It makes to remind a pid alive that doesn't allow your server start. To fix it you have to:
* rm /usr/local/var/postgres/postmaster.pid
* pg_resetxlog -f /usr/local/var/postgres
After this it should run properly if you make the runserver of postgres
Help in Mac OSX: How to start PostgreSQL server on Mac OS X?

Try killing all postgres processes. Im on a MAC and this solution that I've found on ubuntus forum really works.
https://askubuntu.com/questions/547434/how-to-nicely-stop-all-postgres-processes

For Windows
Go to search bar and just write "Open psql" and hit Enter.
Once screen is opened, rerun django project.

In my case, all was set up well and Postgres had the right port, PostgreSQL was running normally, but the 5432 port was being shared with phppgadmin, I could access the phppgadmin that gives me web access to Postgres database server, but my Django application was not working it would return Connection refused error. so I changed the port number on the phppgadmin config file (/etc/phppgadmin/config.inc.php) to 5433 from 5432 and all worked fine.

In MacOS I stopped and restarted postgresql according to the advice given in this StackExchange answer:
https://dba.stackexchange.com/a/171580/182403
brew services stop postgresql
rm /usr/local/var/postgres/postmaster.pid # adjust path accordingly to your install
brew services start postgresql

In project_folder/settings.py under DATABASE - HOST settings you should use local IP (127.0.0.1) not your public IP.
Correct
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'yourdb',
'USER': 'youruser',
'PASSWORD': 'yourpass',
'HOST': '127.0.0.1',
'PORT': '5432'
}
}
Incorrect
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'yourdb',
'USER': 'youruser',
'PASSWORD': 'yourpass',
'HOST': '188.252.196.234 ',
'PORT': '5432'
}
}

I had the same issue. This error occurs when an improper system shutdown has been done. I'm on an M1, and I've installed PostgreSQL via Homebrew.
I tried to start PostgreSQL after receiving an error identical to yours using brew services start postgresql, but I got this error:
Bootstrap failed: 5: Input/output error
Try re-running the command as root for richer errors.
Error: Failure while executing; `/bin/launchctl bootstrap gui/501 /Users/adithraghav/Library/LaunchAgents/homebrew.mxcl.postgresql.plist` exited with 5.
So, I tried to stop the running instance and start it again with brew services restart postgresql.
This line gave me the following output:
Stopping `postgresql`... (might take a while)
==> Successfully stopped `postgresql` (label: homebrew.mxcl.postgresql)
==> Successfully started `postgresql` (label: homebrew.mxcl.postgresql)
I checked the port on which PostgreSQL was running with sudo netstat -nl | grep postgres, but received no output.
So I deleted the existing postmaster.pid file with this:
rm /opt/homebrew/var/postgres/postmaster.pid
NOTE: If you are not on an M1 Mac, you have to run rm /usr/local/var/postgres/postmaster.pid.
Then, I ran pg_resetwal -f /opt/homebrew/var/postgres to reset the write-ahead log. (NOTE: From Postgres 10 and onwards, pg_resetxlog has been renamed to pg_resetwal).
Now, python3 manage.py runserver works with no issues :)

The following command works for me (Windows)-
pg_ctl -D "C:\Program Files\PostgreSQL\11\data" restart
Then run server again-
python manage.py runserver

Restarting the server solved the problem on my side.

In case you are seeing this error while using PostgresSQL from Google Cloud follow all configurations as mentioned in
https://cloud.google.com/python/django/flexible-environment#macos-64-bit
Also separate the HOST configuration as below
DATABASES['default']['HOST'] = '/cloudsql/'
if os.getenv('GAE_INSTANCE'):
pass
else:
DATABASES['default']['HOST'] = '127.0.0.1'
This helps in resolving this error.

Go to aws instance -> security groups -> source -> inbound -> ::0

You might not connecting to the right database. If you are using Docker be sure you are using 5432 as port at the outside of the image.
eg:
db:
image: postgres:12.0-alpine
volumes:
- postgres_data:/var/lib/postgresql/data/
env_file:
- ./postgres/.env
ports:
- 5432:5432

One problem that I found common with Django/Postgres (especially with Docker) is that your Django Web App maybe starting up before your Postgres server starts up. If the other solutions don't work, try to restart your Django App after start up. With Docker, the command would be docker restart <web-app container name>

You have to enable listen addresses if you are using remote database.
cd /etc/postgresql/12.x/main/
open file named postgresql.conf
sudo nano postgresql.conf
add this line to that file
listen_addresses = '*'
then an open a 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

Related

I have Postgres server connection error when I use docker?

My application works fine on my system but when I build a docker image by docker composer and then run the application it shows the error below.
However, I resolved it by changing the ip address from 127.0.0.1 => 0.0.0.0 in the Flask setting as below and the docker image works fine on my system. But when I run it on another ubuntu it gives me the same error and changes the IP to 127.0.0.1.
if __name__ == "__main__":
app.run(host='**0.0.0.0**',debug=False)
ERROR:
Traceback (most recent call last):
File "./main.py", line 22, in <module>
ps.create_table() # create the table if is not existed
File "/prj/Modules/postgres.py", line 49, in create_table
connection = get_connection()
File "/prj/Modules/postgres.py", line 36, in get_connection
return psycopg2.connect(f"dbname={db_name} user={user} password={password} host={host}")
File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 126, in connect
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?
you can have access to my code and my docker hub:
docker hub: applia65/duplicatebugreportsearchengine
Github: https://github.com/ghasemieh/Duplicated-Bug-Report-Detection-System/blob/master/main.py
Basically I have 3 container my-app, Postgres, and MongoDB.
I appreciate it if you help me with this problem.
Thanks
From the trace, the PostgreSql isn't accessible. Can you try updating your docker compose and add expose statement like below:
expose:
- 5432
This will allow access only to the linked services unless "ports" is also specified.

InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (13 Permission denied)

I'm trying to host an application on apache2 server using python CGI framework. The program works fine when compiled and there is no error.
When I try it on the web browser I get the error.
InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (13 Permission denied)
I have tried installing mysql-connector-python and checked if I'm missing anything. Everything seems to be fine. Below is the code with the error in detail.
def connectdb():
mydb = mx.connect(host='localhost',user='******',passwd='********',database='searchdb')
cur=mydb.cursor()
return mydb,cur
Error when trying to access the program.
Traceback (most recent call last):
File "/var/www/html/ftest.py", line 116, in <module>
mydb,cur=connectdb()
File "/var/www/html/ftest.py", line 55, in connectdb
mx.connect(host='localhost',user='*****',passwd='********',database='searchdb')
File "/usr/lib/python2.7/site-packages/mysql/connector/__init__.py", line 98, in connect
return MySQLConnection(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/mysql/connector/connection.py", line 118, in __init__
self.connect(**kwargs)
File "/usr/lib/python2.7/site-packages/mysql/connector/connection.py", line 382, in connect
self._open_connection()
File "/usr/lib/python2.7/site-packages/mysql/connector/connection.py", line 345, in _open_connection
self._socket_open_connection()
File "/usr/lib/python2.7/site-packages/mysql/connector/network.py", line 386, in _open_connection
errno=2003, values=(self.get_address(), _strioerror(err)))
InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (13 Permission denied)
This is the error that I'm facing. Anyone familiar with this issue, Please let me know.
Thank you.
Some things to check, assuming this is a Linux machine:
Make sure you can connect locally using the same user name and password.
mysql -u [youruser] -p
If SELinux is running, make sure the "httpd_can_network_connect_db" boolean is set to on. Check with sudo getsebool httpd_can_network_connect_db. If it comes back as "off," set it to "on" with sudo setsebool -P httpd_can_network_connect_db on. (Make sure to include the -P, or it will revert back to the original value if the system restarts.)

google django "Can't connect to MySQL server on '127.0.0.1'

I am trying use Google app engine to deploy my Django and I followed the steps until "Run the Django migrations to set up your models:"
When I type python manage.py makemigrations and run, it just reports cannot connect.
I do not know why I cannot connect to this port. I have closed my firewall and the IP address is 127.0.0.1. Pymysql is installed already but still cannot connect.
System check identified no issues (0 silenced).
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000002ADF1FA38C8>
Traceback (most recent call last):
File "C:\Users\USER\python-docs-samples\appengine\standard_python37\django\env\lib\site-packages\pymysql\connections.py", line 582, in connect
**kwargs)
File "c:\users\user\appdata\local\programs\python\python37\Lib\socket.py", line 727, in create_connection
raise err
File "c:\users\user\appdata\local\programs\python\python37\Lib\socket.py", line 716, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] 無法連線,因為目標電腦拒絕連線。
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' ([WinError 10061] 無法連線,因為目標電腦拒絕連線。)")
File "C:\Users\USER\python-docs-samples\appengine\standard_python37\django\env\lib\site-packages\pymysql\connections.py", line 629, in connect
raise exc
django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' ([WinError 10061] 無法連線,因為目標電腦拒絕連線。)")
You need to be sure your setting file is filled with the correct db conf:
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': <db_name>,
'USER': <db_username>,
'PASSWORD': <db_password>,
'HOST': 127.0.0.1,
'PORT': 5433,
Then start a proxy connection following this tutorial
My connection command is:
./cloud_sql_proxy -instances=<instance_connection_name>=tcp:5433 -credential_file=<your_credential_file_path>
I set all connection's port to 5433 in my confs because my local postgres db is already listening on the 5432 port.

Odoo installation ''error: [Errno 98] Address already in use''

I followed this installation guide for odoo and I get an error in the very end
when I run odoo-bin file it gives me this error
teo#teo-Lenovo-Yoga-3-14:/opt/odoo/odoo-10.0$ ./odoo-bin
2017-07-06 15:03:20,583 3754 INFO ? odoo: Odoo version 10.0
2017-07-06 15:03:20,583 3754 INFO ? odoo: addons paths: ['/home/teo/.local/share/Odoo/addons/10.0', u'/opt/odoo/odoo-10.0/odoo/addons', u'/opt/odoo/odoo-10.0/addons']
2017-07-06 15:03:20,583 3754 INFO ? odoo: database: default#default:default
2017-07-06 15:03:20,601 3754 INFO ? odoo.service.server: HTTP service (werkzeug) running on 0.0.0.0:8069
Exception in thread odoo.service.httpd:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 251, in http_thread
self.httpd = ThreadedWSGIServerReloadable(self.interface, self.port, app)
File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 106, in __init__
handler=RequestHandler)
File "/usr/lib/python2.7/dist-packages/werkzeug/serving.py", line 440, in __init__
HTTPServer.__init__(self, (host, int(port)), handler)
File "/usr/lib/python2.7/SocketServer.py", line 417, in __init__
self.server_bind()
File "/opt/odoo/odoo-10.0/odoo/service/server.py", line 116, in server_bind
super(ThreadedWSGIServerReloadable, self).server_bind()
File "/usr/lib/python2.7/BaseHTTPServer.py", line 108, in server_bind
SocketServer.TCPServer.server_bind(self)
File "/usr/lib/python2.7/SocketServer.py", line 431, in server_bind
self.socket.bind(self.server_address)
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
error: [Errno 98] Address already in use
I think it may be related to the odoo.conf file because I specify a port but it still assumes de default port 8069
this is my odoo.conf file
[options]
; This is the password that allows database operations:
; admin_passwd = PASSWORD
db_host = False
db_port = 8470
db_user = odoo
db_password = False
addons_path = /opt/odoo/odoo-10.0/addons
;Log Settings
logfile = /var/log/odoo/odoo.log
log_level = error
Does anyone have an idea of what's happening, for the record I tried to install odoo before but failed so I already had DB user created for e.g.
Because odoo service automatically start when system starts, so you have to kill the odoo-service manually, and then run the ./odoo-bin file, at which point you should be able to see odoo running again.
sudo pkill -9 python
By doing this you'll stop python from finding the odoo service process id and subsequently killing that process.
ps aux | grep odoo
sudo kill <process id>
There are multiple pid running with odoo, ending with /etc/odoo-server.conf, which you have to select.
I think the best option is probably
sudo pkill -9 python
All the best, I hope I solved your problem.
Your odoo config has another DB port set, but 8069 is the port used for xmlrpc requests. If you want to change that in config, you have to set xmlrpc_port = 8470.
You getting this error because you have same port busy, you need to kill the existing process and then you can try again.
check process :
ps -aux|grep odoo.py
kill 09 [process id ]
You can check more details of installation tutorial here using Apache2 and WSGI : enter link description here
For this [Errno 98] error you use following two commands:
root#odoo:~# ps aux | grep odoo
Now you getting this type code
postgres 26041 0.1 2.3 1568276 196668 ? Sl Sep25 5:24 python ./odoo-bin
root#odoo:~# sudo kill -9 26041
Then your error will be fix.
[Errno 98] error you use following two commands
Get the id of the process running by following command
root#odoo:~# ps ax | grep servername
Then kill the already running process
sudo kill -9 process_id
You have another process running with the 8069 port. Kill the process killing python.
With the config file in odoo, you can change to different port changing 8069 with xmlrpc_port = 2003.
For example:
[options]
; This is the password that allows database operations:
admin_passwd = admin
db_host = 0.0.0.0
db_port = 5432
db_user = randall
db_password = admin
dbfilter = odoo
addons_path = /usr/lib/python2.7/dist-packages/openerp/addons
addons_path = /software/odoo/10.0/odoo-server/addons,/software/odoo/10.0/custom-addons,
xmlrpc_interface = 127.0.0.1
xmlrpc_port = 2002
Regards,
If your odoo set up, it's already running when you start your ubuntu.
It can be found in
/etc/init.d/odoo-server
Use this command to kill the existing services
ps -ef|grep odoo-bin
sudo kill ####
Solved with #ShivaGuntuku answer, just adding another way to solve the issue:
You're trying to run Odoo on port 8470, but as the error says you (Address already in use), another application is already running on that port (probably, another Odoo process).
So simply kill the process running on that port:
sudo fuser -k 8470/tcp
Then start your Odoo service again.

MySQLdb connection.py "cant connect" with Django

I'm running Django 1.6 with MySQL on pythonanywhere.com. In the bash command line:
mysqldb has been pip installed
i can access mysql database from the command line with $ mysql -h $your_IP =P 3306 -u username -p
However, when I try and run python manage.py syncdb I get an error that ends with this:
File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'mysql.server' (111)")
In my django settings I have
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabasename',
'USER': 'myusername',
'PASSWORD': 'mypassword',
'HOST': 'mysql.server',
'PORT': '3360',
}
}
I tried running python manage.py test and python manage.py testserver and got the exact same error. I tried python -v manage.py etc to get the verbose spit out and it seems a lot of other stuff is failing to import? Could it be that the settings.py isnt being found? The whole set up worked perfectly fine local, and all I've done is push it to the server and changed the database settings.
Any idea???
Your settings read port as 'PORT': '3360', change that to 3306. Also, make sure mysql.server is a valid server host. Or it could just be localhost

Categories