Advertisement
Mochinov

Untitled

Aug 4th, 2022
1,044
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.86 KB | None | 0 0
  1. import csv
  2. import sqlite3
  3. import logging
  4. import pandas as pd
  5.  
  6. logger = logging.getLogger('logger')
  7.  
  8. class LoadingData:
  9.     """
  10.    Класс для загрузки данных из csv в базу данных
  11.  
  12.    Class for load data from csv into data base
  13.    """
  14.  
  15.     def __init__(self, dbase_name: str, table_name: str, name_file: str, *args, **kwargs) -> None:
  16.         self.dbase_name = dbase_name
  17.         self.table_name = table_name
  18.         self.name_file = name_file
  19.  
  20.         # Подключаемся к базе данных / Connecting to the database
  21.         self.connection = sqlite3.connect(self.dbase_name)
  22.  
  23.         # Открываем файл на чтение / Open file for reading
  24.         self._file = open(self.name_file)
  25.         self.content = csv.reader(self._file)
  26.  
  27.         # Получаем название столбцов /
  28.         self._column = self.transform_column()
  29.  
  30.  
  31.         # Выполнить загрузку из файла / Load from file
  32.         self.execute_script()
  33.  
  34.     def execute_input_date(self, cursor, context) -> None:
  35.         """
  36.        
  37.        """
  38.  
  39.         df = pd.DataFrame(self.content)
  40.         for row in df.itertuples():
  41.             cursor.execute(
  42.                 self.insert_structure(),
  43.                 **self.get_rows(row),
  44.             )
  45.            
  46.         # Сохраняем все изменения / Save all changes
  47.         self.connection.commit()
  48.  
  49.     def execute_script(self) -> None:
  50.         """
  51.        Выполняем загрузку данных
  52.  
  53.        Performing data loading
  54.        """
  55.         # Подключаемся к базе / Connecting to the base
  56.         cursor = self.connection.cursor()
  57.  
  58.         # Выполняем создание таблицы исходя из структуры файла / Create table based on file structure
  59.         cursor.execute(self.create_structure())
  60.        
  61.         # Выполняем запись данных / Performing data recording
  62.         print(self.insert_structure(),)
  63.  
  64.         # cursor.executemany(self.insert_structure(), self.content)
  65.         self.execute_input_date(cursor, self.content)
  66.  
  67.     def insert_structure(self) -> str:
  68.         """
  69.        Метод генерирует вставку данных изходя из столбцов файла
  70.  
  71.        The method generates an insertion of data based on the columns of the file
  72.        """
  73.  
  74.         return f'''
  75.            INSERT INTO {self.table_name} ({', '.join([_ for _ in self._column])}) VALUES({', '.join(['?' for _ in range(len(self._column))])})
  76.        '''
  77.  
  78.     def create_structure(self) -> str:
  79.         """
  80.        The method generates the table creation structure
  81.  
  82.        Метод генерирует структуру созданиея таблицы
  83.        """
  84.         sql_fields = ",\n".join([f"{sql_structure} TEXT" for sql_structure in self._column[1:]])
  85.  
  86.         create_table = f'''
  87.            CREATE TABLE {self.table_name}(
  88.                id INTEGER PRIMARY KEY AUTOINCREMENT,
  89.                {sql_fields}
  90.            );
  91.        '''
  92.  
  93.         return create_table
  94.  
  95.     def transform_column(self) -> list:
  96.         """
  97.        Преобразует название столбцов
  98.  
  99.        Converts column names
  100.        """
  101.         structure = list(self.content)[0]
  102.         return [_.lower().replace(' ', '_') for _ in structure]
  103.  
  104.     def get_rows(self, obj) -> list:
  105.         """
  106.        Получение атрибутов объекта
  107.        """
  108.        
  109.         return [obj._ for _ in self._column]
  110.  
  111.     def __del__(self) -> None:
  112.         """Закрытие потока / Closing a stream"""
  113.  
  114.         self._file.close()
  115.         self.connection.close()
  116.  
  117.  
  118. db = LoadingData(
  119.     "departament.sqlite",
  120.     "departament",
  121.     "police-department-calls-for-service.csv",
  122. )
  123.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement