Forum Stats

  • 3,759,900 Users
  • 2,251,613 Discussions
  • 7,870,859 Comments

Discussions

django.db.utils.DatabaseError: ORA-12541: TNS:no listener

Tony007
Tony007 Member Posts: 4,151 Bronze Trophy
edited Aug 21, 2021 5:39PM in Python

hi am trying to connect to my database am geting this error my database is up and listner


python manage.py runserver


Watching for file changes with StatReloader


Performing system checks...




System check identified no issues (0 silenced).


Exception in thread django-main-thread:


Traceback (most recent call last):


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection


 self.connect()


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner


 return func(*args, **kwargs)


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 200, in connect


 self.connection = self.get_new_connection(conn_params)


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner


 return func(*args, **kwargs)


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/backends/oracle/base.py", line 233, in get_new_connection


 **conn_params,


cx_Oracle.DatabaseError: ORA-12541: TNS:no listener




The above exception was the direct cause of the following exception:




Traceback (most recent call last):


 File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner


 self.run()


 File "/usr/lib/python3.6/threading.py", line 864, in run


 self._target(*self._args, **self._kwargs)


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, in wrapper


 fn(*args, **kwargs)


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run


 self.check_migrations()


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/core/management/base.py", line 486, in check_migrations


 executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__


 self.loader = MigrationLoader(self.connection)


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 53, in __init__


 self.build_graph()


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 220, in build_graph


 self.applied_migrations = recorder.applied_migrations()


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations


 if self.has_table():


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 55, in has_table


 with self.connection.cursor() as cursor:


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner


 return func(*args, **kwargs)


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 259, in cursor


 return self._cursor()


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 235, in _cursor


 self.ensure_connection()


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner


 return func(*args, **kwargs)


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection


 self.connect()


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__


 raise dj_exc_value.with_traceback(traceback) from exc_value


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection


 self.connect()


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner


 return func(*args, **kwargs)


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 200, in connect


 self.connection = self.get_new_connection(conn_params)


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner


 return func(*args, **kwargs)


 File "/home/django/Documents/pythonreact/ReactProj/django-backend/.venv/lib/python3.6/site-packages/django/db/backends/oracle/base.py", line 233, in get_new_connection


 **conn_params,


django.db.utils.DatabaseError: ORA-12541: TNS:no listener




my server listner


status


Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=199.777.7.111)(PORT=1539)))


STATUS of the LISTENER


------------------------


Alias      LISTENER


Version     TNSLSNR for Linux: Version 19.0.0.0.0 - Production


Start Date    09-JUL-2021 07:04:29


Uptime     2 days 1 hr. 2 min. 29 sec


Trace Level    off


Security     ON: Local OS Authentication


SNMP      OFF


Listener Parameter File /u1/app/oracle/product/19.0.0/dbhome_1/network/admin/listener.ora


Listener Log File   /u1/app/oracle/product/19.0.0/dbhome_1/network/log/listener.log


Listening Endpoints Summary...


 (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=199.777.7.111)(PORT=1539)))


 (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1521)))


 (DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=hostname)(PORT=5500))(Security=(my_wallet_directory=/u1/app/oracle/admin/dbname/xdb_wallet))(Presentation=HTTP)(Session=RAW))


 (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=hostname)(PORT=8081))(Presentation=HTTP)(Session=RAW))


Services Summary...


Service "dbname" has 2 instance(s).


 Instance "dbname", status UNKNOWN, has 1 handler(s) for this service...


 Instance "dbname", status READY, has 1 handler(s) for this service...


Service "ncsalphaXDB" has 1 instance(s).


 Instance "dbname", status READY, has 1 handler(s) for this service...


The command completed successfully


LSNRCTL> status


Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=199.777.7.111)(PORT=1539)))


STATUS of the LISTENER


------------------------


Alias      LISTENER


Version     TNSLSNR for Linux: Version 19.0.0.0.0 - Production


Start Date    09-JUL-2021 07:04:29


Uptime     2 days 1 hr. 2 min. 56 sec


Trace Level    off


Security     ON: Local OS Authentication


SNMP      OFF


Listener Parameter File /u1/app/oracle/product/19.0.0/dbhome_1/network/admin/listener.ora


Listener Log File   /u1/app/oracle/product/19.0.0/dbhome_1/network/log/listener.log


Listening Endpoints Summary...


 (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=199.777.7.111)(PORT=1539)))


 (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1521)))


 (DESCRIPTION=(ADDRESS=(PROTOCOL=tcps)(HOST=hostname)(PORT=5500))(Security=(my_wallet_directory=/u1/app/oracle/admin/dbname/xdb_wallet))(Presentation=HTTP)(Session=RAW))


 (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=hostname)(PORT=8081))(Presentation=HTTP)(Session=RAW))


Services Summary...


Service "dbname" has 2 instance(s).


 Instance "dbname", status UNKNOWN, has 1 handler(s) for this service...


 Instance "dbname", status READY, has 1 handler(s) for this service...


Service "dbnameXDB" has 1 instance(s).


 Instance "dbname", status READY, has 1 handler(s) for this service...


The command completed successfully


LSNRCTL> service


Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=199.777.7.111)(PORT=1539)))


Services Summary...


Service "dbname" has 2 instance(s).


 Instance "dbname", status UNKNOWN, has 1 handler(s) for this service...


 Handler(s):


  "DEDICATED" established:0 refused:0


   LOCAL SERVER


 Instance "dbname", status READY, has 1 handler(s) for this service...


 Handler(s):


  "DEDICATED" established:275 refused:0 state:ready


   LOCAL SERVER


Service "ncsalphaXDB" has 1 instance(s).


 Instance "dbname", status READY, has 1 handler(s) for this service...


 Handler(s):


  "D000" established:0 refused:0 current:0 max:1022 state:ready


   DISPATCHER <machine: hostname, pid: 2679>


   (ADDRESS=(PROTOCOL=tcp)(HOST=hostname)(PORT=25278))


The command completed successfully


LSNRCTL> !


NL-00853: undefined command "!". Try "help"


LSNRCTL> exit


[[email protected] ~]$ cat /etc/hosts


127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4


::1   localhost localhost.localdomain localhost6 localhost6.localdomain6




199.777.7.111 hostname

Answers

  • Christopher Jones-Oracle
    Christopher Jones-Oracle Member Posts: 1,643 Employee

    Start by checking that SQL*Plus (not SQL Developer) can connect.

    Then try a Python program that calls cx_Oracle directly (not using Django).

    This post has some useful tips that apply to all apps connecting to a remote DB: https://www.thatjeffsmith.com/archive/2014/09/ora-12545-12541-12514-01017/

  • Roland Mueller
    Roland Mueller Member Posts: 78 Blue Ribbon

    Before running Django app you should of course check

    • whether the listener is up & running in DB machine
    • whether you can connect from host where django app is running to DB server+DB port. DB port is 1521 by default, but in the text I saw 1539 mentioned
    • connection check can be done using nmap or simply the telnet client app: 'telnet DB_HOST PORT'


    Shouldn't connecting to Oracle DB using the default port 1521 in this way in settings.py?

    • variables DB_HOSTNAME and SID_OR_SERVICE are set in same settings.py

    'default': {

            'ENGINE': 'django.db.backends.oracle',

            'NAME': DB_HOSTNAME + ':1521/' + SID_OR_SERVICE,

            'USER': 'user',

            'PASSWORD': 'pass',

        }

    With other port 1521 has to be replaced.

  • Christopher Jones-Oracle
    Christopher Jones-Oracle Member Posts: 1,643 Employee

    One note: 'SID_OR_SERVICE' should be 'SERVICE' since the 'easy connect' syntax doesn't support SIDs.

    A couple of recent blog posts might be of interest:

    https://blogs.oracle.com/opal/connecting-to-oracle-cloud-autonomous-database-with-django

    https://blogs.oracle.com/opal/running-oracle-database-backed-django-web-applications-on-apache

  • Tony007
    Tony007 Member Posts: 4,151 Bronze Trophy
    edited Aug 21, 2021 5:45PM

    this my setting

    """

    Django settings for mysite project.


    Generated by 'django-admin startproject' using Django 2.0.2.


    For more information on this file, see

    https://docs.djangoproject.com/en/2.0/topics/settings/


    For the full list of settings and their values, see

    https://docs.djangoproject.com/en/2.0/ref/settings/

    """


    import os


    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)

    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))



    # Quick-start development settings - unsuitable for production

    # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/


    # SECURITY WARNING: keep the secret key used in production secret!

    SECRET_KEY = '39tl#ywdu(^i#u2f-rosga7vn)&uchp^h96myvl4wo80a=+4g*'


    # SECURITY WARNING: don't run with debug turned on in production!

    DEBUG = True


    ALLOWED_HOSTS = []



    # Application definition


    INSTALLED_APPS = [

      'django.contrib.admin',

      'django.contrib.auth',

      'django.contrib.contenttypes',

      'django.contrib.sessions',

      'django.contrib.messages',

      'django.contrib.staticfiles',

      'accounts',

      'oauth2_provider',

      'rest_framework',


    ]


    MIDDLEWARE = [

      'corsheaders.middleware.CorsMiddleware',

      'corsheaders.middleware.CorsPostCsrfMiddleware',

      'django.middleware.security.SecurityMiddleware',

      'django.contrib.sessions.middleware.SessionMiddleware',

      'django.middleware.common.CommonMiddleware',

      'django.middleware.csrf.CsrfViewMiddleware',

      'django.contrib.auth.middleware.AuthenticationMiddleware',

      'django.contrib.messages.middleware.MessageMiddleware',

      'django.middleware.clickjacking.XFrameOptionsMiddleware',

    ]


    ROOT_URLCONF = 'mysite.urls'


    TEMPLATES = [

      {

        'BACKEND': 'django.template.backends.django.DjangoTemplates',

        'DIRS': [],

        'APP_DIRS': True,

        'OPTIONS': {

          'context_processors': [

            'django.template.context_processors.debug',

            'django.template.context_processors.request',

            'django.contrib.auth.context_processors.auth',

            'django.contrib.messages.context_processors.messages',

          ],

        },

      },

    ]


    WSGI_APPLICATION = 'mysite.wsgi.application'



    # Database

    # https://docs.djangoproject.com/en/2.0/ref/settings/#databases


    DATABASES = {

      'default': {

        'ENGINE': 'django.db.backends.oracle',

        'NAME': 'dbname',

        'USER': 'username',

        'PASSWORD': 'password',

        'PORT': '1539',

        'HOST': '199.154.7.188'

      }

    }



    # Password validation

    # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators


    AUTH_PASSWORD_VALIDATORS = [

      {

        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',

      },

      {

        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',

      },

      {

        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',

      },

      {

        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',

      },

    ]



    # Internationalization

    # https://docs.djangoproject.com/en/2.0/topics/i18n/


    LANGUAGE_CODE = 'en-us'


    TIME_ZONE = 'UTC'


    USE_I18N = True


    USE_L10N = True


    USE_TZ = True



    # Static files (CSS, JavaScript, Images)

    # https://docs.djangoproject.com/en/2.0/howto/static-files/


    STATIC_URL = '/static/'


    AUTH_USER_MODEL = 'accounts.User'


    CORS_ORIGIN_ALLOW_ALL = True


    OAUTH2_PROVIDER = {

      # this is the list of available scopes

      'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}

    }


    REST_FRAMEWORK = {

      # Use Django's standard `django.contrib.auth` permissions,

      # or allow read-only access for unauthenticated users.

      'DEFAULT_AUTHENTICATION_CLASSES': (

        'rest_framework.authentication.BasicAuthentication',

        'rest_framework.authentication.SessionAuthentication',

        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',

      )

    }


     telnet 199.128.2.111:1539

    telnet: could not resolve 192.168.8.123:1539/telnet: Name or service not known

  • Christopher Jones-Oracle
    Christopher Jones-Oracle Member Posts: 1,643 Employee

    If you are having network issues, install SQL*Plus (not SQL Developer) on the machine where you run Python and make sure you can connect to the database using that. Then the same connection string will be usable in Django (assuming it runs in the same environment)