ClanStat/app/db.py

58 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Импорт модулей стандартной библиотеки
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)))
self.commit()
cur.close()
return True