• Python上下文管理器


    在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()
    
  • 相关阅读:
    C# Using MySQL
    C++ Asynchronous IO on Windows
    C++ Bind adapter usage
    C# Entity Framework with MSSQL, MYSQL
    Read a file into array for C++/C#
    上下移动 04.16
    盒子模型001基础
    JavaScript&JQ 001_五角星评分
    jQuery EasyUI tree的 使用
    自定义实现URL重写 04.18
  • 原文地址:https://www.cnblogs.com/enochmeng/p/14892818.html
Copyright © 2020-2023  润新知