dimanche 6 octobre 2019

How correct open connections to database in Python/Django

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 ?

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):

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

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()

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 .

Aucun commentaire:

Enregistrer un commentaire