通过一个例子展示 with 语句的用法
需求:打开一个文件,并打印文件内容
files = open(‘/file.txt‘)
content = files.read()
print(files.read())
files.close()
with open(‘/file.txe‘) as files:
content = files.read()
print(content)
这两种写法实现的功能是一样的,使用 with 语句少了一行代码 files.close(),这行代码的意思是关闭打开的文件,这个动作是必要的,如果不关闭文件,文件会一直打开。
with 语句能够帮助程序完成 close() 这个动作,而不用我们每次都要记住关闭已打开的文件。哪 with 语句是怎么实现,或者说是怎么提供这种功能的呢?
答案是:python 的上下文管理器,with 语句会接收上下文管理器,并能绝对的完成上下文管理器定义的任务,即使程序抛异常了。
通过上面的描述,我们已经知道,open() 方法其实也是一个上下文管理器。
其实上下文管理器我们也可以自己实现并通过 with 调用,实现一个 上下文管理器的方法分为三部分:
init 方法主要用于管理器的数据初始化,enter 方法是管理器的主要逻辑,exit 方法是清理操作,比如 close() 方法就可以卸载 exit 方法里面
这里实现一个数据库连接的上下文管理器
"""
mysql的上下文管理器
示例:
from DBcm import UseDatabase
config = {‘host‘: ‘127.0.0.1‘,
‘user‘: ‘user‘,
‘password‘: ‘pwd‘,
‘database‘: ‘datebase‘}
with UseDatabase as cursor:
_SQL = "select * from log"
cursor.execute(_SQL)
data = cursor.fetchall()
"""
class UseDatabase:
def __init__(self, config: dict) -> None:
"""传入一个config参数,主要包含mysql数据连接需要使用的:
地址host,登录账户名username,登录账户密码password,使用的库database
"""
self.configuration = config
def __enter__(self) -> cursors:
"""使用pymysql库,连接数据库,并返回一个游标cursor"""
try:
self.conn = pymysql.connect(**self.configuration)
self.cursor = self.conn.cursor()
return self.cursor
except pymysql.InterfaceError as error:
raise ConnectionError(error) # 用raise产生一个数据连接异常,并返回一个跟踪信息
except pymysql.ProgrammingError as error:
raise CredentialsError(error) # 用raise产生一个数据库操作权限异常,并返回一个跟踪信息
def __exit__(self, exc_type, exc_value, exc_traceback) -> None:
"""在完成数据库交互后,执行清理工作,关闭游标cursor,以及断开mysql连接"""
self.conn.commit()
self.cursor.close()
self.conn.close()
if exc_type is pymysql.ProgrammingError:
raise SQLErrot(exc_value)
elif exc_value:
raise exc_type(exc_value)
学习内容来自《Head First Python》
原文:https://www.cnblogs.com/garden-mion/p/14258502.html