Skip to content

Commit

Permalink
Переделал метод запроса в бд
Browse files Browse the repository at this point in the history
  • Loading branch information
KAnanev committed Jul 4, 2023
1 parent c668cc5 commit 9e511aa
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 29 deletions.
2 changes: 1 addition & 1 deletion page_analyzer/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def init_db():
db = get_db()

with current_app.open_resource('database.sql') as f:
db.raw_execute(f.read().decode('utf8'))
db.execute_query(f.read().decode('utf8'))


@click.command('init-db')
Expand Down
53 changes: 26 additions & 27 deletions page_analyzer/services/db.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import psycopg
import logging
from typing import Optional
from typing import Optional, List, Tuple, Any

from psycopg.rows import dict_row

Expand All @@ -11,45 +11,44 @@ def __init__(self, dsn):
self.logger = logging.getLogger(__name__)

try:
self.connect = psycopg.connect(dsn, row_factory=dict_row)
self.connection = psycopg.connect(dsn, row_factory=dict_row)
except Exception as e:
self.logger.error(f"Ошибка при подключении к базе данных: {str(e)}")

def close(self) -> None:

"""Закрывает соединение с базой данных"""

self.connect.close()
self.connection.close()
self.logger.info("Соединение с базой данных закрыто")

def raw_execute(self, query: str) -> None:
connect = self.connect
try:
connect.execute(query)
connect.commit()
except Exception as e:
self.logger.error(f"Ошибка при выполнении запроса: {str(e)}")
connect.rollback()
def execute_query(self,
query: str,
params: Optional[tuple] = None,
commit: bool = False) -> Optional[list[Any]]:
"""Запрос к бд"""

def execute_query(
self, query: str,
params: Optional[tuple] = None,
commit: bool = False
) -> Optional[list]:
"""Выполняет SQL-запрос к базе данных"""

connect = self.connect
result = None
cursor = self.connection.cursor()

try:
result = connect.execute(query, params).fetchall()
cursor.execute(query, params)

if cursor.description:
result = cursor.fetchall()

if commit:
connect.commit()
return result
except Exception as e:
self.connection.commit()

except psycopg.Error as e:
self.logger.error(f"Ошибка при выполнении запроса: {str(e)}")
connect.rollback()
return None

finally:
if cursor:
cursor.close()

return result

def is_closed(self):
if self.connect:
return self.connect.closed
if self.connection:
return self.connection.closed
2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def app():
with app.app_context():
db = get_db()
init_db()
db.raw_execute(_test_data_sql)
db.execute_query(_test_data_sql)

yield app

Expand Down
8 changes: 8 additions & 0 deletions tests/test_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,11 @@ def test_get_close_db(app):
db.execute_query('SELECT 1')

assert 'closed' in str(error.value)


def test_get_data_db(app):
with app.app_context():
db = get_db()
result = db.execute_query('select * from urls;')
assert result[0]['id'] == 1
assert result[1]['id'] == 2

0 comments on commit 9e511aa

Please sign in to comment.