python上下文管理器简单实现

# 简单的实现上下文管理器
class Mysource:
    def __enter__(self):
        print('connect to resource')
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('close resource connection')
    def query(self):
        print('query data')

with Mysource() as r: # r就是__enter__ return回来的
    r.query()

# 使用contextmanager实现上下文管理器
class Myresource1:
    def query(self):
        print('使用contextmanager实现的上下文管理器')

from contextlib import contextmanager

@contextmanager
def make_mysource():
    print('connect to resource1')
    yield Myresource1()
    print('close resource connection1')

with make_mysource() as r:
    r.query()

#使用上下文管理器实现自动数据库查询的commit
from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy

class SQLAlchemy(_SQLAlchemy):
    def auto_commit(self):
        try:
            yield
            self.session.commit()
        except Exception as e:
            self.session.rollback()
            raise e
db = SQLAlchemy()

#涉及数据库查询的地方,可以快速实现数据的commit及异常的捕获
with db.auto_commit():
    user = User()
    user.set_attrs(form.data)
    db.session.add()

你可能感兴趣的:(知识累积)