jenkins-bot has submitted this change and it was merged. ( https://gerrit.wikimedia.org/r/605855 )
Change subject: [IMPR] use contextlib.closing to close connection and cursor in mysql.py ......................................................................
[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(-)
Approvals: Dvorapa: Looks good to me, approved jenkins-bot: Verified
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
pywikibot-commits@lists.wikimedia.org