python装饰器类型错误_Python:类内装饰器的使用(pymongo自动重连实现)

0x00

最近要实现一个pymongo库的自动重连功能,但是官方文档只说了:

In order to auto-reconnect you must handle this exception, recognizing that the operation which caused it has not necessarily succeeded. Future operations will attempt to open a new connection to the database (and will continue to raise this exception until the first successful connection is made).

大概意思就是。。想要自动重连?自己捕获异常重连吧~

因此,这里简易地用装饰器来实现一个自动重连的功能。

0x01

重连函数

def reconnect(func):

""" Reconnect decorator. """

@wraps(func)

def wrapper(self, *args, **kwargs):

""" Wrapper. """

try:

return func(self, *args, **kwargs)

except errors.AutoReconnect:

logger.warning('[W] Reconnecting to database.')

#self.connect()

return wrapper(self, *args, **kwargs)

return wrapper

这里采用装饰器的方式,当捕获到函数运行时的AutoReconnect错误时,就自动重连。

因为我采用的是类封装,因此传入了self参数。(这个函数不能定义在类里,定义在类外面。)

0x02

封装的数据库类

class Database:

"""

Database class

"""

def __init__(self):

self.connect()

def connect(self):

""" Database connect function. """

self.client = MongoClient(host=config['DATABASE_HOST'], \

authSource=config['DATABASE_NAME'], \

username=config['DATABASE_USER'], \

password=config['DATABASE_PASSWORD'])

logger.info("[+] Database connected.")

@reconnect

def insert_one(self, database, collection, document):

""" Insert one document into specific database collection. """

return self.client[database][collection].insert_one(document).inserted_id

大概就像这样,在可能需要重连的操作函数上加上@reconnect装饰即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值