66 lines
1.9 KiB
Python
66 lines
1.9 KiB
Python
# Импорт модулей стандартной библиотеки
|
||
import json
|
||
|
||
# Импорт сторонних модулей
|
||
import psycopg2
|
||
|
||
|
||
class DataBase(object):
|
||
"""Класс для работы с базой данных"""
|
||
|
||
def __init__(self, host: str, port: int, name: str, user: str, password: str):
|
||
super(DataBase, self).__init__()
|
||
self.host = host
|
||
"""Хост PostgreSQL базы данных"""
|
||
self.port = port
|
||
"""Порт сервера базы данных"""
|
||
self.name = name
|
||
"""Имя базы данных"""
|
||
self.user = user
|
||
"""Имя пользователя"""
|
||
self.password = password
|
||
"""Пароль пользователя"""
|
||
|
||
def connect(self) -> bool:
|
||
"""Выполняет подключение к базе данных"""
|
||
self.conn = psycopg2.connect(
|
||
dbname=self.name,
|
||
host=self.host,
|
||
user=self.user,
|
||
password=self.password,
|
||
port=self.port,
|
||
)
|
||
return True
|
||
|
||
def close(self) -> bool:
|
||
"""Закрывает подключение к базе данных"""
|
||
self.conn.close()
|
||
return True
|
||
|
||
def commit(self) -> None:
|
||
"""Выполняет коммит"""
|
||
self.conn.commit()
|
||
return True
|
||
|
||
def add_data(self, data, wins: bool) -> bool: # wins изменит на Enum
|
||
"""Добавляет данные в базу данных"""
|
||
if wins:
|
||
table = 'wins'
|
||
else:
|
||
table = 'donates'
|
||
|
||
cur = self.conn.cursor()
|
||
cur.execute(
|
||
'INSERT INTO {table} ("data") VALUES (\'{data}\')'.format(
|
||
table=table,
|
||
data=json.dumps(
|
||
data,
|
||
ensure_ascii=False,
|
||
),
|
||
)
|
||
)
|
||
self.commit()
|
||
cur.close()
|
||
|
||
return True
|