Skip to content

Commit 944934f

Browse files
author
Kareem Zidane
committed
abstract away catch_warnings
1 parent 7f9b77c commit 944934f

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

src/cs50/_sql_util.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
"""Utility functions used by sql.py"""
22

3+
import contextlib
34
import decimal
5+
import warnings
46

57

68
def fetch_select_result(result):
@@ -17,3 +19,10 @@ def fetch_select_result(result):
1719
row[column] = bytes(row[column])
1820

1921
return rows
22+
23+
24+
@contextlib.contextmanager
25+
def raise_errors_for_warnings():
26+
with warnings.catch_warnings():
27+
warnings.simplefilter("error")
28+
yield

src/cs50/sql.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
"""Wraps SQLAlchemy"""
22

33
import logging
4-
import warnings
54

65
import sqlalchemy
76
import termcolor
87

98
from ._session import Session
109
from ._statement import statement_factory
11-
from ._sql_util import fetch_select_result
10+
from ._sql_util import fetch_select_result, raise_errors_for_warnings
1211

1312
_logger = logging.getLogger("cs50")
1413

@@ -55,10 +54,7 @@ def execute(self, sql, *args, **kwargs):
5554
return ret
5655

5756
def _execute(self, statement):
58-
# Catch SQLAlchemy warnings
59-
with warnings.catch_warnings():
60-
# Raise exceptions for warnings
61-
warnings.simplefilter("error")
57+
with raise_errors_for_warnings():
6258
try:
6359
result = self._session.execute(statement)
6460
except sqlalchemy.exc.IntegrityError as exc:

0 commit comments

Comments
 (0)