在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()