AttributeError:__enter__连接到mysql数据库期间

时间:2019-10-09 05:54:35

标签: python python-3.x

在执行以下代码以获取连接和光标时,我得到 AttributeError:__enter __

from contextlib import closing
def _connect():
    return closing(mysql.connect(
        host=settings.DATABASES['data_base_name'].get('HOST', 'localhost'),
        user=settings.DATABASES['data_base_name']['USER'],
        passwd=settings.DATABASES['data_base_name'].get('PASSWORD', ''),
        db=settings.DATABASES['data_base_name']['NAME'],
        cursorclass=cursors.DictCursor))

with _connect() as conn, conn as cursor:

执行过程中出现以下错误。

with _connect() as conn, conn as cursor:
 AttributeError: __enter__

2 个答案:

答案 0 :(得分:0)

我已经使用ContextDecorator解决了我的问题,如下所示。

from contextlib import ContextDecorator

class my_connect(ContextDecorator):
    def __init__(self):
        self.data_base_connection = ''

    def __enter__(self):
        self.data_base_connection = mysql.connect(
        host=settings.DATABASES['data_base_name'].get('HOST', 'localhost'),
        user=settings.DATABASES['data_base_name']['USER'],
        passwd=settings.DATABASES['data_base_name'].get('PASSWORD', ''),
        db=settings.DATABASES['data_base_name']['NAME'],
        cursorclass=cursors.DictCursor)
        cursor = self.data_base_name.cursor()
        return cursor

    def __exit__(self, *exc):
        self.data_base_connection.close()
        return False

在query_tables()中,我只需使用 with 关键字

调用my_connect()
def query_tables():
    with my_connect() as cursor:
        #rest of the statements

答案 1 :(得分:0)

您也可以通过这种方式使用您的初始方法来实现。你不需要创建一个类。在内部,它会通过创建一个类来完成您所做的工作,但恕我直言,代码更简洁。

from contextlib import contextmanager

@contextmanager
def _connect():
    data_base_connection = mysql.connect(
    host=settings.DATABASES['data_base_name'].get('HOST', 'localhost'),
    user=settings.DATABASES['data_base_name']['USER'],
    passwd=settings.DATABASES['data_base_name'].get('PASSWORD', ''),
    db=settings.DATABASES['data_base_name']['NAME'],
    cursorclass=cursors.DictCursor)
    try:
       yield data_base_connection
    finally:
        data_base_connection.close()

def query_tables():
    with _connect() as conn:
        cursor = conn.cursor()
        # rest of the statements