Python上下文管理器
阿新 • • 發佈:2021-06-17
在python指令碼工具中,配合with使用上下文管理器的寫法將會非常nice,比如進行資料庫操作,郵件傳送等等一些具有連線、關閉的操作時。
- 第一種函式的寫法
"""以傳送郵件為例""" import smtplib from contextlib import contextmanager SMTP_SERVER = "" ACCOUNT = "" PASSWORD = "" @contextmanager def connect(): smtp_obj = smtplib.SMTP(SMTP_SERVER) smtp_obj.login(ACCOUNT, PASSWORD) yield smtp_obj smtp_obj.quit()
- 第二種類的寫法
"""以連線資料庫為例""" import pymysql import pymysql.cursors from collections import namedtuple DBConfig = namedtuple( "DBConfig", ['ip', 'user', 'pwd', 'port'], defaults=["127.0.0.1", "", "", 0] ) DBMap = {...} class Connect: def __init__(self, key, dbname): self.cfg = DBMap[key] self.dbname = dbname def __enter__(self): self.conn = pymysql.connect( host=self.cfg.ip, user=self.cfg.user, password=self.cfg.pwd, database=self.dbname, port=self.cfg.port, ) self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor) return self.cursor def __exit__(self, exc_type, exc_val, exc_tb): self.cursor.close() self.conn.close() class ConnectAndCommit(Connect): def __exit__(self, exc_type, exc_val, exc_tb): self.conn.commit() self.cursor.close() self.conn.close()