python context manager 上下文管理器

上下文管理器即 with 语句,这是 python 独有的语句。

with 常用于文件操作,with 语句执行结束后被打开的文件自动关闭,代码更简洁:

with open("myfile.txt", 'r') as file:
       pass

其中,open 是一个class。

也可以实现自定义的 上下文管理器,例如,如下数据库操作代码有很多重复,不管是创建,更新还是删除,每次都要连接数据库,关闭数据库,为了避免这种重复,可以将这些每次都要执行的代码写到一个上下文管理器,即一个类中。

def get_all_books():
    connection = sqlite3.connect('data.db')
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM books")
    books = [{'name': row[0], 'author': row[1], 'read': row[2]} for row in cursor.fetchall()]
    connection.close()
    return books
def add_book(name, author):
    connection = sqlite3.connect('data.db')
    cursor = connection.cursor()
    cursor.execute(f'INSERT INTO books VALUES(?, ?, 0)', (name, author))
    connection.commit()
    connection.close()

上下文管理器的实现:

import sqlite3


class DatabaseConnection:
    def __init__(self, host):
        self.connection = None
        self.host = host

    def __enter__(self):
        self.connection = sqlite3.connect(self.host)
        return self.connection

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type or exc_val or exc_tb:  # in case of any error, close the connection without commit
            self.connection.close()
        else:
            self.connection.commit()
            self.connection.close()

数据库的代码因此可以简化:

def add_book(name, author):
    with DatabaseConnection('data.db') as connection:
        cursor = connection.cursor()
        cursor.execute(f'INSERT INTO books VALUES(?, ?, 0)', (name, author))


def get_all_books():
    with DatabaseConnection('data.db') as connection:
        cursor = connection.cursor()
        cursor.execute("SELECT * FROM books")
        books = [{'name': row[0], 'author': row[1], 'read': row[2]} for row in cursor.fetchall()]
    return books
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值