jenkins-bot merged this change.

View Change

Approvals: Dvorapa: Looks good to me, approved jenkins-bot: Verified
[IMPR] use contextlib.closing to close connection and cursor in mysql.py

- use contextlib.closing to close connection and cursor in mysql.py.
This closes connection and cursor even id an error occurs inside the
with block.

Change-Id: I45c90afc4158b5555ed421904dc1fcef7068e062
---
M pywikibot/data/mysql.py
1 file changed, 19 insertions(+), 21 deletions(-)

diff --git a/pywikibot/data/mysql.py b/pywikibot/data/mysql.py
index 05186c3..2b40bf1 100644
--- a/pywikibot/data/mysql.py
+++ b/pywikibot/data/mysql.py
@@ -7,6 +7,8 @@
#
from __future__ import absolute_import, division, unicode_literals

+from contextlib import closing
+
import pywikibot

try:
@@ -57,28 +59,24 @@
else:
credentials = {'read_default_file': config.db_connect_file}

- conn = pymysql.connect(config.db_hostname,
- db=config.db_name_format.format(dbname),
- port=config.db_port,
- charset='utf8',
- **credentials)
+ with closing(pymysql.connect(config.db_hostname,
+ db=config.db_name_format.format(dbname),
+ port=config.db_port,
+ charset='utf8',
+ **credentials)) as conn, \
+ closing(conn.cursor()) as cursor:

- cursor = conn.cursor()
+ if verbose:
+ _query = cursor.mogrify(query, params)

- if verbose:
- _query = cursor.mogrify(query, params)
+ if not isinstance(_query, UnicodeType):
+ _query = UnicodeType(_query, encoding='utf-8')
+ _query = _query.strip()
+ _query = '\n'.join(' {0}'.format(line)
+ for line in _query.splitlines())
+ pywikibot.output('Executing query:\n' + _query)

- if not isinstance(_query, UnicodeType):
- _query = UnicodeType(_query, encoding='utf-8')
- _query = _query.strip()
- _query = '\n'.join(' {0}'.format(line)
- for line in _query.splitlines())
- pywikibot.output('Executing query:\n' + _query)
+ cursor.execute(query, params)

- cursor.execute(query, params)
-
- for row in cursor:
- yield row
-
- cursor.close()
- conn.close()
+ for row in cursor:
+ yield row

To view, visit change 605855. To unsubscribe, or for help writing mail filters, visit settings.

Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-MessageType: merged
Gerrit-Change-Id: I45c90afc4158b5555ed421904dc1fcef7068e062
Gerrit-Change-Number: 605855
Gerrit-PatchSet: 2
Gerrit-Owner: Xqt <info@gno.de>
Gerrit-Reviewer: Dvorapa <dvorapa@seznam.cz>
Gerrit-Reviewer: Mpaa <mpaa.wiki@gmail.com>
Gerrit-Reviewer: jenkins-bot (75)