Created
September 29, 2020 20:34
-
-
Save anna-anisienia/e795cd5b9e8214a41b1ad42a9e9da9d7 to your computer and use it in GitHub Desktop.
context manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import contextlib | |
import mysql.connector | |
@contextlib.contextmanager | |
def get_mysql_conn(db): | |
""" | |
Context manager to automatically close DB connection. | |
We retrieve credentials from Environment variables | |
""" | |
conn = mysql.connector.connect(host=os.environ.get('MYSQL_HOST'), | |
user=os.environ.get('MYSQL_USER'), | |
password=os.environ.get('MYSQL_PWD'), | |
database=db) | |
try: | |
yield conn | |
finally: | |
conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment