Connecting Django docker to remote database - django

I have a Django application running on docker connected to a database in another container on the same host. This seams to work fine, but when I try to change the connection to a database on another server, it fails to connect. Not only that, but when I try to connect to the Django application in the browser(like admin or api) I get no response, and see no activity in the output log. The application runs fine with the remote database if I run it outside the container, and the database is set to accept all IPs for the user I am trying to connect with.
Any Ideas as to why I am not getting a connection?
Dockerfile:
FROM python:3.8-alpine
ENV PATH="/scripts:${PATH}"
COPY ./requirements.txt /requirements.txt
RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers
RUN apk add mariadb-dev python3-dev postgresql-dev
RUN pip install -r /requirements.txt
RUN apk del .tmp
RUN mkdir /app_django
COPY ./app_django /app_django
WORKDIR /app_django
COPY ./scripts /scripts
RUN chmod +x /scripts/*
RUN mkdir -p /vol/web/media
RUN mkdir -p /vol/web/static
RUN adduser -D user
RUN chown -R user:user /vol
RUN chmod -R 755 /vol/web
USER user
CMD ["entrypoint.sh"]
docker-compose.yml
version: '3.7'
services:
db:
build: mysql/
environment:
MYSQL_ROOT_PASSWORD: 'password'
MYSQL_DATABASE: database
volumes:
- ./mysql/data:/var/lib/mysql
- ./mysql/conf:/etc/mysql/conf.d
- ./mysql/entrypoint-initdb.d:/docker-entrypoint-initdb.d/
- ./mysql/backup_database:/var/local/mysql/backups
ports:
- 3306:3306
restart: always
pdb:
build:
context: .
ports:
- "8000:8000"
volumes:
- ./pdb_django:/pdb_django
command: sh -c "python manage.py runserver 0.0.0.0:8000"
environment:
- DEBUG=1
entrypoint.sh
#!/bin/sh
set -e
python manage.py collectstatic --noinput
uwsgi --socket :8000 --master --enable-threads --module app.wsgi
Django db settings (the commented parts is used when conection to db on host container):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'database',
'HOST': '<remote IP>',
# 'HOST': 'db',
'USER': 'user',
'PASSWORD': 'password',
'PORT': '3308'
# 'PORT': '3306',
}
}
requirements.txt
Django==3.1.4
uWSGI>=2.0.18,<2.1
django-filter==2.4.0
djangorestframework==3.12.2
mysql-connector-python==8.0.22
mysqlclient==2.0.2
PyMySQL==0.10.1
sqlparse==0.4.1
Outputlog for application:
pdb_1 | Watching for file changes with StatReloader
pdb_1 | Exception in thread django-main-thread:
pdb_1 | Traceback (most recent call last):
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
pdb_1 | self.connect()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
pdb_1 | return func(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect
pdb_1 | self.connection = self.get_new_connection(conn_params)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
pdb_1 | return func(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 234, in get_new_connection
pdb_1 | return Database.connect(**conn_params)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 130, in Connect
pdb_1 | return Connection(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 185, in __init__
pdb_1 | super().__init__(*args, **kwargs2)
pdb_1 | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on '<remote IP>' (115)")
pdb_1 |
pdb_1 | The above exception was the direct cause of the following exception:
pdb_1 |
pdb_1 | Traceback (most recent call last):
pdb_1 | File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner
pdb_1 | self.run()
pdb_1 | File "/usr/local/lib/python3.8/threading.py", line 870, in run
pdb_1 | self._target(*self._args, **self._kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
pdb_1 | fn(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run
pdb_1 | self.check_migrations()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 459, in check_migrations
pdb_1 | executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__
pdb_1 | self.loader = MigrationLoader(self.connection)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__
pdb_1 | self.build_graph()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 216, in build_graph
pdb_1 | self.applied_migrations = recorder.applied_migrations()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
pdb_1 | if self.has_table():
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 55, in has_table
pdb_1 | with self.connection.cursor() as cursor:
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
pdb_1 | return func(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor
pdb_1 | return self._cursor()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 235, in _cursor
pdb_1 | self.ensure_connection()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
pdb_1 | return func(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
pdb_1 | self.connect()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
pdb_1 | raise dj_exc_value.with_traceback(traceback) from exc_value
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
pdb_1 | self.connect()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
pdb_1 | return func(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect
pdb_1 | self.connection = self.get_new_connection(conn_params)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
pdb_1 | return func(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 234, in get_new_connection
pdb_1 | return Database.connect(**conn_params)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 130, in Connect
pdb_1 | return Connection(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 185, in __init__
pdb_1 | super().__init__(*args, **kwargs2)
pdb_1 | django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '<remote IP>' (115)")

It would seem this was an issue with my VPN. When I tried to run the container on a server on the network it worked fine, and I was also able to get responses when I turned off my VPN (although I could obviously not access the database on the server)

Related

Create superuser for cvat

I am trying to install cvat, so I am following the Installation guide
The first step run smoothly, however when I try to create a superuser with the command
docker exec -it cvat_server bash -ic 'python3 ~/manage.py createsuperuser'
After a few minutes, I get the following error:
Traceback (most recent call last):
File "/opt/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/opt/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner
return func(*args, **kwargs)
File "/opt/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "/opt/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner
return func(*args, **kwargs)
File "/opt/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "/opt/venv/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not connect to server: Connection timed out
Is the server running on host "cvat_db" (172.18.0.3) and accepting
TCP/IP connections on port 5432?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/django/manage.py", line 21, in <module>
execute_from_command_line(sys.argv)
File "/opt/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
utility.execute()
File "/opt/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/opt/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "/opt/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute
return super().execute(*args, **options)
File "/opt/venv/lib/python3.8/site-packages/django/core/management/base.py", line 397, in execute
self.check_migrations()
File "/opt/venv/lib/python3.8/site-packages/django/core/management/base.py", line 486, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "/opt/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/opt/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__
self.build_graph()
File "/opt/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 220, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/opt/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
if self.has_table():
File "/opt/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 55, in has_table
with self.connection.cursor() as cursor:
File "/opt/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner
return func(*args, **kwargs)
File "/opt/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor
return self._cursor()
File "/opt/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 235, in _cursor
self.ensure_connection()
File "/opt/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner
return func(*args, **kwargs)
File "/opt/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/opt/venv/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/opt/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/opt/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner
return func(*args, **kwargs)
File "/opt/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "/opt/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner
return func(*args, **kwargs)
File "/opt/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "/opt/venv/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: could not connect to server: Connection timed out
Is the server running on host "cvat_db" (172.18.0.3) and accepting
TCP/IP connections on port 5432?
What should I do to fix this and use CVAT?
My Ubuntu version: Ubuntu 22.04.1 LTS
I thought adding Django's authentication system might solve it so I did pip install django-auth but it changed nothing
I have had the same problem but I found a solution. Some user suggested a problem with docker installation here. My way to solve it is:
Remove docker installation completely. This can help.
Install docker from the atp repository:
sudo apt install containerd
sudo apt install docker.io
Do everything as in the CVAT installation guide, but ignore the part about installing Docker and use the commands above. With this solution some comands indicated in the installation guide will require sudo. In the guide:
Instead of docker compose up -d use sudo docker-compose up -d
Run with sudo docker-compose up

AWS Postgresql RDS instance "does not exist" with docker-compose and Django

My RDS and web container are not connected.
But I did all the database-related settings in Django's settings, and I also set up AWS RDS properly.
What should I do more?
This is DATABASES of settings file of Django.
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": env("SQL_DATABASE"),
"USER": env("SQL_USER"),
"PASSWORD": env("SQL_PASSWORD"),
"HOST": env("SQL_HOST"),
"PORT": env("SQL_PORT"),
}
}
I skipped the docker-compose.yml with nginx-proxy or TLS.
When I tested in local, I made and mounted DB containers on docker-compose, but in prod environments, I didn't make DB containers because I use AWS RDS.
Will this be a problem?
Please help me.
(ps.All of PROJECT_NAME replaced the actual project name.)
This is my docker-compose.yml
version: '3.8'
services:
web:
build:
context: .
dockerfile: prod.Dockerfile
image: project:web
command: gunicorn PROJECT_NAME.wsgi:application --bind 0.0.0.0:8000
env_file:
- envs/.env.prod
volumes:
- static_volume:/home/app/web/static
- media_volume:/home/app/web/media
expose:
- 8000
entrypoint:
- sh
- config/docker/entrypoint.prod.sh
volumes:
static_volume:
media_volume:
This is what I've got error from docker
Waiting for postgres...
PostgreSQL started
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: FATAL: database "db-PROJECT_NAME-ec2" does not exist
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 92, in handle
executor = MigrationExecutor(connection, self.migration_progress_callback)
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__
self.build_graph()
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 216, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
if self.has_table():
File "/usr/local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 55, in has_table
with self.connection.cursor() as cursor:
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor
return self._cursor()
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 235, in _cursor
self.ensure_connection()
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: FATAL: database "db-PROJECT_NAME-ec2" does not exist
[2021-09-18 15:09:21 +0000] [1] [INFO] Starting gunicorn 20.0.4
[2021-09-18 15:09:21 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
[2021-09-18 15:09:21 +0000] [1] [INFO] Using worker: sync
[2021-09-18 15:09:21 +0000] [12] [INFO] Booting worker with pid: 12
Highly likely the reason is that the AWS RDS DB instance name differs from PostgreSQL DB name.
As per AWS RDS manual
For Databases, choose the name of the new DB instance.
On the RDS console, the details for the new DB instance appear. The DB instance has a status of creating until the DB instance is created and ready for use. When the state changes to available, you can connect to the DB instance. Depending on the DB instance class and storage allocated, it can take several minutes for the new instance to be available.
As per PostgreSQL: Documentation
dbname
Specifies the name of the database to be created. The name must be unique among all PostgreSQL databases in this cluster. The default is to create a database with the same name as the current system user.
Default dbname is postgres
So, you may want to try postgres instead db-PROJECT_NAME-ec2 as a DB name.

Django + Mongo + Docker getting pymongo.errors.ServerSelectionTimeoutError

I've been struggling to get a simple app running using Django, Djongo, Mongo, and Docker Compose. My setup looks like this:
docker-compose.yml
services:
mongodb:
image: mongo:latest
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: mongoadmin
MONGO_INITDB_DATABASE: django_mongodb_docker
ports:
- 27017:27017
web:
build: ./src
restart: always
command: python src/manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- 8000:8000
links:
- mongodb
Dockerfile
FROM python:3
ENV PYTHONUNBUFFERED=1
RUN mkdir /code
COPY . /code/
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
settings.py
DATABASES = {
'default': {
'ENGINE': 'djongo',
'HOST': 'mongodb',
'PORT': 27017,
'USER': 'root',
'PASSWORD': 'mongoadmin',
'AUTH_SOURCE': 'admin',
'AUTH_MECHANISM': 'SCRAM-SHA-1',
}
}
What is annoying is that I am able to use pymongo from my web container to connect to the container running mongo. That works as follows.
from pymongo import MongoClient
c = MongoClient(
'mongodb://mongodb:27017',
username='root',
password='mongoadmin',
authSource='admin',
authMechanism='SCRAM-SHA-1')
print(c.server_info())
The issue is that when I go to run migrations from within my web container I get the following error.
Traceback (most recent call last):
File "/code/src/manage.py", line 22, in <module>
main()
File "/code/src/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 92, in handle
executor = MigrationExecutor(connection, self.migration_progress_callback)
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__
self.build_graph()
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 216, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
if self.has_table():
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 56, in has_table
tables = self.connection.introspection.table_names(cursor)
File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/introspection.py", line 48, in table_names
return get_names(cursor)
File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/introspection.py", line 43, in get_names
return sorted(ti.name for ti in self.get_table_list(cursor)
File "/usr/local/lib/python3.9/site-packages/djongo/introspection.py", line 47, in get_table_list
for c in cursor.db_conn.list_collection_names()
File "/usr/local/lib/python3.9/site-packages/pymongo/database.py", line 863, in list_collection_names
for result in self.list_collections(session=session, **kwargs)]
File "/usr/local/lib/python3.9/site-packages/pymongo/database.py", line 825, in list_collections
return self.__client._retryable_read(
File "/usr/local/lib/python3.9/site-packages/pymongo/mongo_client.py", line 1460, in _retryable_read
server = self._select_server(
File "/usr/local/lib/python3.9/site-packages/pymongo/mongo_client.py", line 1278, in _select_server
server = topology.select_server(server_selector)
File "/usr/local/lib/python3.9/site-packages/pymongo/topology.py", line 241, in select_server
return random.choice(self.select_servers(selector,
File "/usr/local/lib/python3.9/site-packages/pymongo/topology.py", line 199, in select_servers
server_descriptions = self._select_servers_loop(
File "/usr/local/lib/python3.9/site-packages/pymongo/topology.py", line 215, in _select_servers_loop
raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5f9ecaa5bbdc0433baa13966, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]>
In addition, I've tried to create a Djongo model and save it to see if maybe the problem is specific to migrations (essentially just trying to make any connection to mongo using djongo).
models.py
from djongo import models
class Blog(models.Model):
name = models.CharField(max_length=100)
test.py
b = Blog(name='test')
b.save()
That returns the following error:
The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/cursor.py", line 51, in execute
web_1 | self.result = Query(
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 783, in __init__
web_1 | self._query = self.parse()
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 884, in parse
web_1 | raise exe from e
web_1 | djongo.exceptions.SQLDecodeError:
web_1 |
web_1 | Keyword: None
web_1 | Sub SQL: None
web_1 | FAILED SQL: INSERT INTO "game_blog" ("name") VALUES (%(0)s)
web_1 | Params: ['test']
web_1 | Version: 1.3.3
web_1 |
web_1 | The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
web_1 | return self.cursor.execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/cursor.py", line 59, in execute
web_1 | raise db_exe from e
web_1 | djongo.database.DatabaseError
web_1 |
web_1 | The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
web_1 | response = get_response(request)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response
web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
web_1 | return self.dispatch(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/views/generic/base.py", line 98, in dispatch
web_1 | return handler(request, *args, **kwargs)
web_1 | File "/code/src/game/views.py", line 9, in get
web_1 | b.save(using='mongo')
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 753, in save
web_1 | self.save_base(using=using, force_insert=force_insert,
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 790, in save_base
web_1 | updated = self._save_table(
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 895, in _save_table
web_1 | results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 933, in _do_insert
web_1 | return manager._insert(
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
web_1 | return getattr(self.get_queryset(), name)(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1254, in _insert
web_1 | return query.get_compiler(using=using).execute_sql(returning_fields)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1397, in execute_sql
web_1 | cursor.execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute
web_1 | return super().execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute
web_1 | return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
web_1 | return executor(sql, params, many, context)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
web_1 | return self.cursor.execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__
web_1 | raise dj_exc_value.with_traceback(traceback) from exc_value
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
web_1 | return self.cursor.execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/cursor.py", line 59, in execute
web_1 | raise db_exe from e
web_1 | django.db.utils.DatabaseError
Any help on this would be greatly appreciated.
I have tried editing my mongodb.conf like this already.
According to this document, the settings.py should have a CLIENT section which contains:
A set of key-value pairs that will be passed directly to MongoClient as kwargs while creating a new client connection.
So try setting your settings.py to:
DATABASE = {
'default': {
'ENGINE': 'djongo',
'NAME': 'your-database-name',
'CLIENT': {
'host': 'mongodb://mongodb:27017',
'username': 'root',
'password': 'mongoadmin',
'authSource': 'admin',
'authMechanism': 'SCRAM-SHA-1',
}
}
}

Django oracle its not working [duplicate]

I just want to connect my local oracle db with my django project but my database credential is not working. Actually, I'm able to connect my oracle database via sql developer with that credential:
I just used that credential in django settings_py like that
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'INTERNAL',
'USER': 'system',
'PASSWORD': 'oracle',
'HOST':'localhost/xe',
'PORT':'1521'
}
}
and error is:
Traceback (most recent call last):
web_1 | File "manage.py", line 22, in <module>
web_1 | execute_from_command_line(sys.argv)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
web_1 | utility.execute()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
web_1 | self.fetch_command(subcommand).run_from_argv(self.argv)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
web_1 | self.execute(*args, **cmd_options)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
web_1 | output = self.handle(*args, **options)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 110, in handle
web_1 | loader.check_consistent_history(connection)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 282, in check_consistent_history
web_1 | applied = recorder.applied_migrations()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
web_1 | self.ensure_schema()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema
web_1 | if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()):
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 254, in cursor
web_1 | return self._cursor()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 229, in _cursor
web_1 | self.ensure_connection()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection
web_1 | self.connect()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
web_1 | six.reraise(dj_exc_type, dj_exc_value, traceback)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
web_1 | raise value.with_traceback(tb)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection
web_1 | self.connect()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect
web_1 | self.connection = self.get_new_connection(conn_params)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/oracle/base.py", line 212, in get_new_connection
web_1 | return Database.connect(self._connect_string(), **conn_params)
web_1 | django.db.utils.DatabaseError: ORA-12545: Connect failed because target host or object does not exist
here its my listener status
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC_FOR_XE)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for Linux: Version 11.2.0.2.0 - Production
Start Date 28-DEC-2017 15:51:21
Uptime 0 days 2 hr. 8 min. 36 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Default Service XE
Listener Parameter File /u01/app/oracle/product/11.2.0/xe/network/admin/listener.ora
Listener Log File /u01/app/oracle/diag/tnslsnr/e48c7c272f44/listener/alert/log.xml
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC_FOR_XE)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=e48c7c272f44)(PORT=1521)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=e48c7c272f44)(PORT=8080))(Presentation=HTTP)(Session=RAW))
Services Summary...
Service "PLSExtProc" has 1 instance(s).
Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
Service "XE" has 1 instance(s).
Instance "XE", status READY, has 1 handler(s) for this service...
Service "XEXDB" has 1 instance(s).
Instance "XE", status READY, has 1 handler(s) for this service...
here its my listener status
You should change HOST to localhost' or '127.0.0.1 and SID is NAME.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'xe',
'USER': 'system',
'PASSWORD': 'oracle',
'HOST':'127.0.0.1',
'PORT':'1521'
}
}
For future references, if Oracle is configured with Service name instead of SID, then the configuration would be:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': '127.0.0.1:1521/service.name',
'USER': 'system',
'PASSWORD': 'oracle',
}
}
Another thing to consider when working with Oracle in Django is that when you connect to Other Users (schema) database, you have to set db_table Meta option in Django models:
class OracleTable(models.Model):
... fields ...
class Meta:
db_table = '\"OTHERUSER\".\"ORACLETABLE\"'

Django oracle db settings

I just want to connect my local oracle db with my django project but my database credential is not working. Actually, I'm able to connect my oracle database via sql developer with that credential:
I just used that credential in django settings_py like that
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'INTERNAL',
'USER': 'system',
'PASSWORD': 'oracle',
'HOST':'localhost/xe',
'PORT':'1521'
}
}
and error is:
Traceback (most recent call last):
web_1 | File "manage.py", line 22, in <module>
web_1 | execute_from_command_line(sys.argv)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
web_1 | utility.execute()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
web_1 | self.fetch_command(subcommand).run_from_argv(self.argv)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
web_1 | self.execute(*args, **cmd_options)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
web_1 | output = self.handle(*args, **options)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 110, in handle
web_1 | loader.check_consistent_history(connection)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 282, in check_consistent_history
web_1 | applied = recorder.applied_migrations()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
web_1 | self.ensure_schema()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema
web_1 | if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()):
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 254, in cursor
web_1 | return self._cursor()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 229, in _cursor
web_1 | self.ensure_connection()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection
web_1 | self.connect()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
web_1 | six.reraise(dj_exc_type, dj_exc_value, traceback)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
web_1 | raise value.with_traceback(tb)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection
web_1 | self.connect()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect
web_1 | self.connection = self.get_new_connection(conn_params)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/oracle/base.py", line 212, in get_new_connection
web_1 | return Database.connect(self._connect_string(), **conn_params)
web_1 | django.db.utils.DatabaseError: ORA-12545: Connect failed because target host or object does not exist
here its my listener status
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC_FOR_XE)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for Linux: Version 11.2.0.2.0 - Production
Start Date 28-DEC-2017 15:51:21
Uptime 0 days 2 hr. 8 min. 36 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Default Service XE
Listener Parameter File /u01/app/oracle/product/11.2.0/xe/network/admin/listener.ora
Listener Log File /u01/app/oracle/diag/tnslsnr/e48c7c272f44/listener/alert/log.xml
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC_FOR_XE)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=e48c7c272f44)(PORT=1521)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=e48c7c272f44)(PORT=8080))(Presentation=HTTP)(Session=RAW))
Services Summary...
Service "PLSExtProc" has 1 instance(s).
Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
Service "XE" has 1 instance(s).
Instance "XE", status READY, has 1 handler(s) for this service...
Service "XEXDB" has 1 instance(s).
Instance "XE", status READY, has 1 handler(s) for this service...
here its my listener status
You should change HOST to localhost' or '127.0.0.1 and SID is NAME.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'xe',
'USER': 'system',
'PASSWORD': 'oracle',
'HOST':'127.0.0.1',
'PORT':'1521'
}
}
For future references, if Oracle is configured with Service name instead of SID, then the configuration would be:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': '127.0.0.1:1521/service.name',
'USER': 'system',
'PASSWORD': 'oracle',
}
}
Another thing to consider when working with Oracle in Django is that when you connect to Other Users (schema) database, you have to set db_table Meta option in Django models:
class OracleTable(models.Model):
... fields ...
class Meta:
db_table = '\"OTHERUSER\".\"ORACLETABLE\"'