Отказано в соединении при использовании MongoDB с Django - PullRequest
0 голосов
/ 31 марта 2020

Я использую 2 базы данных для моего Django проекта, и они находятся в настройках следующим образом:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'AppDB',
        'USER': 'genericpiratename',
        'PASSWORD':'pass',
        'HOST': 'mypirateapp-postgres.ja6as4d8ss54.ap-south-1.rds.amazonaws.com',
        'PORT': '5432',
    },
    'mongoDB' : {
        'ENGINE': 'djongo',
        'NAME': 'pirateapp',
        'USER': 'uncommonpiratename',
        'PASSWORD': 'dbpass',
        'HOST': 'mongodb+srv://uncommonpiratename:dbpass@cluster1-8zu5ge.mongodb.net/test',
    }
}

Первая база данных - это размещенная база данных PostgreSQL, а вторая также размещенная база данных MongoDB. Я использовал атлас mongodb для размещения кластера и компаса для создания базы данных pirateapp. Я также разрешил доступ к базам данных для обеих баз данных со всех IP-адресов.

Я использовал следующие базы данных для баз данных:

class PrimaryRouter:
    def db_for_read(self, model, **hints):
        return 'default'

    def db_for_write(self, model, **hints):
        return 'default'

    def allow_relation(self, obj1, obj2, **hints):
        db_list = ('default')
        if obj1._state.db in db_list and obj2._state.db in db_list:
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return True


class DirectionsRouter:
    route_app_labels = {'tressureHunter'}

    def db_for_read(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'mongoDB'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'mongoDB'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if (
            obj1._meta.app_label in self.route_app_labels or
            obj2._meta.app_label in self.route_app_labels
        ):
           return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in self.route_app_labels:
            return db == 'mongoDB'
        return None

Я также указал правильный путь к маршрутизаторам в настройках как:

DATABASE_ROUTERS = ['services.dataRouters.PrimaryRouter', 'services.dataRouters.DirectionsRouter']

После этого, когда я делаю python3 manage.py makemigrations, он показывает следующую ошибку:

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute
    output = self.handle(*args, **options)
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle
    loader.check_consistent_history(connection)
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history
    applied = recorder.applied_migrations()
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations
    if self.has_table():
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table
    return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/django/db/backends/base/introspection.py", line 48, in table_names
    return get_names(cursor)
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/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 "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/djongo/introspection.py", line 47, in get_table_list
    for c in cursor.db_conn.list_collection_names()
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/pymongo/database.py", line 856, in list_collection_names
    for result in self.list_collections(session=session, **kwargs)]
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/pymongo/database.py", line 819, in list_collections
    _cmd, read_pref, session)
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1454, in _retryable_read
    read_pref, session, address=address)
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1253, in _select_server
    server = topology.select_server(server_selector)
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/pymongo/topology.py", line 235, in select_server
    address))
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/pymongo/topology.py", line 193, in select_servers
    selector, server_timeout, address)
  File "/home/suraj/Work/Speeve/speeve-backend/speeveEnv/lib/python3.6/site-packages/pymongo/topology.py", line 209, in _select_servers_loop
    self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused

Я использую Django версию 3.0.3 и Djon go версия двигателя 1.3.1

Пожалуйста, помогите!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...