Last active
August 3, 2019 13:18
-
-
Save danmichaelo/e2da9a7f645397650fa0caea5897d899 to your computer and use it in GitHub Desktop.
PyMySQL Force Unicode Cursors (because sometimes use_unicode=True is not enough)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from pymysql.cursors import Cursor, DictCursor | |
| class ForceUnicodeMixin(): | |
| def _ensure_unicode_value(self, value): | |
| if isinstance(value, bytes) or isinstance(value, bytearray): | |
| return value.decode('utf-8') | |
| return value | |
| def _ensure_unicode(self, row): | |
| return [self._ensure_unicode_value(value) for value in row] | |
| class ForceUnicodeCursor(Cursor): | |
| def _do_get_result(self): | |
| conn = self._get_db() | |
| self._result = result = conn._result | |
| self.rowcount = result.affected_rows | |
| self.description = result.description | |
| self.lastrowid = result.insert_id | |
| self._rows = [self._ensure_unicode(row) for row in result.rows] | |
| class ForceUnicodeDictCursor(DictCursor): | |
| def _conv_row(self, row): | |
| if row is None: | |
| return None | |
| return self.dict_type(zip(self._fields, self._ensure_unicode(row))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pymysql.cursors | |
| from .force_unicode_cursors import ForceUnicodeDictCursor | |
| db = pymysql.connect( | |
| cursorclass=ForceUnicodeDictCursor, | |
| host=DB_HOST, | |
| port=DB_PORT, | |
| db=DB_DB, | |
| user=DB_USER, | |
| password=DB_PASSWORD, | |
| ) | |
| db.ping(True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment