我正在 python 中实现一个数据库连接器类。我将使用retry
tenacity 库中的装饰器在超时时重试数据库连接。
我想将self.retry_count
and传递给装饰器self.retry_interval
中的参数。retry
## etl_connect.py
from sqlalchemy import create_engine
import pymysql
import logging
from tenacity import *
class Connector():
def __init__(self, mode, conn_str, retry_count, retry_interval):
self.mode = mode
self.conn_str = conn_str
self.retry_count = retry_count
self.retry_interval = retry_interval
self.engine = None
self.conn = None
@retry(wait=wait_fixed(self.retry_interval), stop=stop_after_attempt(self.retry_count))
def mysql_connect(self):
logging.info('Connecting to mysql. (retry count=%d)' % (self.mysql_connect.retry.statistics['attempt_number']))
mysql_engine = create_engine(self.conn_str)
mysql_conn = mysql_engine.connect()
logging.info('Connected to mysql successfully with %d attempt(s).' % (self.mysql_connect.retry.statistics['attempt_number']))
return (mysql_engine, mysql_conn)
现在调用mysql_connect
函数:
## call.py
from etl_connect import *
mysql_connector = Connector('mysql', 'mysql database string here', 5, 10)
engine, conn = mysql_connector.mysql_connect()
但它显示:NameError: name 'self' is not defined
.
Traceback (most recent call last):
File "call.py", line 5, in <module>
from etl_connect import *
File "/home/developer/ETL_modules/etl_connect.py", line 19, in <module>
class Connector():
File "/home/developer/ETL_modules/etl_connect.py", line 56, in Connector
@retry(wait=wait_fixed(self.retry_interval), stop=stop_after_attempt(self.retry_count))
NameError: name 'self' is not defined
有什么方法可以将self.retry_count
&传递self.retry_interval
给装饰者吗?