美文网首页
Python实现Mysql数据库连接(使用装饰器检查参数)

Python实现Mysql数据库连接(使用装饰器检查参数)

作者: 李白开水 | 来源:发表于2020-02-28 22:49 被阅读0次

简单实现如下:
Python实现Mysql数据库连接

主函数部分再链接里有相应的注释~

完整代码:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb as db
import functools
import inspect


# 如果decorator本身需要传入参数,那就需要编写一个返回decorator的高阶函数,也就是在外面在嵌套一层check_required_args()
def check_required_args(parameters):
    """check parameters of action"""

    def decorated(f):
        """decorator"""

        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            """wrapper"""
            func_args = inspect.getcallargs(f, *args, **kwargs)
            kwargs = func_args.get('kwargs')
            for item in parameters:
                if kwargs.get(item) is None:
                    message = "check required args failed, `{0}` is not found in {1}".format(item, f.__name__)
                    raise Exception(message)

            return f(*args, **kwargs)

        return wrapper

    return decorated


@check_required_args(['user', 'passwd', 'host'])    #带参数的装饰器,此处的参数必须在主函数的get_conn中有,没有会报错
def get_conn(**kwargs):
    return db.connect(host=kwargs.get('host', 'localhost'),
                      user=kwargs.get('user'),
                      passwd=kwargs.get('passwd'),
                      port=kwargs.get('port', 3306),
                      db=kwargs.get('db'))


def main():
    conn = get_conn(host='127.0.0.1',
                    user='root',
                    passwd='hahaha',
                    db='hehehe')
    cur = conn.cursor()

    cur.execute("select * from lalala")
    print(cur.fetchall())

    cur.close()
    conn.close()


if __name__ == '__main__':
    main()

缺少参数的报错信息如下:


image.png

对于inspect包的详细信息参照:
python--inspect模块

对于functools包的详细信息参照:
Python functools.wraps 深入理解

相关文章

网友评论

      本文标题:Python实现Mysql数据库连接(使用装饰器检查参数)

      本文链接:https://www.haomeiwen.com/subject/yflrhhtx.html