title: How correct open connections to database in Python/Django
body: <p>I want know how open correctly new connection to database. A problem rise when i want create single QUERY to database, from many places in my code. For example, one request is sent to database from login.html , second from register page, third to gallery in index.html . I guess , should i use some project patterns? Do you have some suggestion ?</p>
  
  <p>I have written this class which are responsible for connection to mysql database. I suppose that it is very wrong (i don't focus yet on validation - but i know about that):</p>
  
  <pre class="lang-py prettyprint-override"><code>import mysql.connector
  import configparser
  
  
  class DataBaseConnectionHandler(object):
      __DATABASE = ""
      user = ""
      passwd = ""
      host = ""
      fileName = ""
      dataBaseConnection = ""
  
      def __init__(self, fileName=None, host='localhost'):
  
          if fileName is not None:
              config_file = configparser.ConfigParser()
              config_file.read('shop/config/dbConfig.ini')
  
              database: str = config_file.get('DEFAULT', 'database')
              user: str = config_file.get('DEFAULT', 'user')
              password: str = config_file.get('DEFAULT', 'password')
              self.__DATABASE = database
              self.user = user
              self.passwd = password
              self.host = host
  
      def connectToDatabase(self):
  
          """ EXECUTE CONNECTION AND RETURN AN HOOK TO DATABASE"""
  
          dataBaseConnector = mysql.connector.connect(
              host=self.host,
              user=self.user,
              passwd=self.passwd,
              database=self.__DATABASE
          )
  
          if dataBaseConnector != "":
              self.dataBaseConnection = dataBaseConnector
              return self.dataBaseConnection
          else:
              self.dataBaseConnection = None
              return self.dataBaseConnection
  
  </code></pre>
  
  <p>class RegisterUser</p>
  
  <pre class="lang-py prettyprint-override"><code>from .databses import DataBaseConnection
  
  
  class RegisterUser(object):
      __formName = ""
      __formLogin = ""
      __formSurrname = ""
      __formPasswd = ""
      __fromEmail = ""
  
      def __init__(self, userName, userSurrname, userLogin, userPassword, userEmail):
  
          self.__formName         = userName
          self.__formSurrname     = userSurrname
          self.__formLogin        = userLogin
          self.__formPasswd       = userPassword
          self.__fromEmail        = userEmail
  
      def createUser(self):
  
          print("[!] Create user")
          # ------------- CONNECTION TO DATABASE ----------------
          hook = DataBaseConnection.DataBaseConnectionHandler('shop/config/dbConfig.ini').connectToDatabase()
          myCursor = hook.cursor()
  
          # ------------- EXECUTING MYSQL QUERY ----------------
  
          # [!] nie szyfruje hasła
          sqlStatment = "INSERT INTO user(Login, Password, Email, Name, Surname) " \
                        "VALUES ('{}', '{}', '{}', '{}', '{}');".format(self.__formLogin,
                                                                        self.__formPasswd,
                                                                        self.__fromEmail,
                                                                        self.__formName,
                                                                        self.__formSurrname)
          myCursor.execute(sqlStatment)
          hook.commit()
  
          print(myCursor.rowcount, "Record inserted")
          print("[*] Executing an query")
  
  
          # ------------- CLOSE CONNECTION ----------------
  
          hook.close()
  </code></pre>
  
  <p>I know that Django has own way to connect to database, but it is wired for me. i had some wired error, that why i decide use PyMysql. In near time I'll change that, but it's good moment to learn how to write code correctly .</p>
  
  <p>edit:</p>
  
  <pre><code>PycharmProjects/lovLevelMusic/lovLevelMusic/settings.py changed, reloading.
  Watching for file changes with StatReloader
  Exception in thread django-main-thread:
  Traceback (most recent call last):
    File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
      self.run()
    File "/usr/lib/python3.7/threading.py", line 870, in run
      self._target(*self._args, **self._kwargs)
    File "/usr/local/lib/python3.7/dist-packages/django/utils/autoreload.py", line 54, in wrapper
      fn(*args, **kwargs)
    File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/runserver.py", line 109, in inner_run
      autoreload.raise_last_exception()
    File "/usr/local/lib/python3.7/dist-packages/django/utils/autoreload.py", line 77, in raise_last_exception
      raise _exception[1]
    File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 337, in execute
      autoreload.check_errors(django.setup)()
    File "/usr/local/lib/python3.7/dist-packages/django/utils/autoreload.py", line 54, in wrapper
      fn(*args, **kwargs)
    File "/usr/local/lib/python3.7/dist-packages/django/__init__.py", line 24, in setup
      apps.populate(settings.INSTALLED_APPS)
    File "/usr/local/lib/python3.7/dist-packages/django/apps/registry.py", line 114, in populate
      app_config.import_models()
    File "/usr/local/lib/python3.7/dist-packages/django/apps/config.py", line 211, in import_models
      self.models_module = import_module(models_module_name)
    File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module
      return _bootstrap._gcd_import(name[level:], package, level)
    File "&lt;frozen importlib._bootstrap&gt;", line 1006, in _gcd_import
    File "&lt;frozen importlib._bootstrap&gt;", line 983, in _find_and_load
    File "&lt;frozen importlib._bootstrap&gt;", line 967, in _find_and_load_unlocked
    File "&lt;frozen importlib._bootstrap&gt;", line 677, in _load_unlocked
    File "&lt;frozen importlib._bootstrap_external&gt;", line 728, in exec_module
    File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed
    File "/usr/local/lib/python3.7/dist-packages/django/contrib/auth/models.py", line 2, in &lt;module&gt;
      from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
    File "/usr/local/lib/python3.7/dist-packages/django/contrib/auth/base_user.py", line 47, in &lt;module&gt;
      class AbstractBaseUser(models.Model):
    File "/usr/local/lib/python3.7/dist-packages/django/db/models/base.py", line 117, in __new__
      new_class.add_to_class('_meta', Options(meta, app_label))
    File "/usr/local/lib/python3.7/dist-packages/django/db/models/base.py", line 321, in add_to_class
      value.contribute_to_class(cls, name)
    File "/usr/local/lib/python3.7/dist-packages/django/db/models/options.py", line 204, in contribute_to_class
      self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
    File "/usr/local/lib/python3.7/dist-packages/django/db/__init__.py", line 28, in __getattr__
      return getattr(connections[DEFAULT_DB_ALIAS], item)
    File "/usr/local/lib/python3.7/dist-packages/django/db/utils.py", line 201, in __getitem__
      backend = load_backend(db['ENGINE'])
    File "/usr/local/lib/python3.7/dist-packages/django/db/utils.py", line 110, in load_backend
      return import_module('%s.base' % backend_name)
    File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module
      return _bootstrap._gcd_import(name[level:], package, level)
    File "/usr/local/lib/python3.7/dist-packages/django/db/backends/mysql/base.py", line 22, in &lt;module&gt;
      from MySQLdb.constants import CLIENT, FIELD_TYPE                # isort:skip
  ImportError: cannot import name 'CLIENT' from 'MySQLdb.constants' (unknown location)
  </code></pre>
  
  <p>settings.py</p>
  
  <pre><code>DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.mysql',
         'NAME': 'dbDjango',
         'USER': 'root',
         'PASSWORD': 'password',
         'HOST': '127.0.0.1',
         'PORT': '3306',
     }
  }
  </code></pre>