29 lines
696 B
Python
29 lines
696 B
Python
from contextlib import contextmanager
|
|
from typing import Iterator
|
|
|
|
import pymysql
|
|
from pymysql.connections import Connection
|
|
|
|
from config import CONFIG
|
|
|
|
|
|
@contextmanager
|
|
def db_connection() -> Iterator[Connection]:
|
|
connection = pymysql.connect(
|
|
host=CONFIG.db_host,
|
|
port=CONFIG.db_port,
|
|
user=CONFIG.db_user,
|
|
password=CONFIG.db_password,
|
|
database=CONFIG.db_name,
|
|
charset=CONFIG.db_charset,
|
|
cursorclass=pymysql.cursors.DictCursor,
|
|
autocommit=True,
|
|
connect_timeout=CONFIG.db_connect_timeout,
|
|
read_timeout=20,
|
|
write_timeout=20,
|
|
)
|
|
try:
|
|
yield connection
|
|
finally:
|
|
connection.close()
|