【问题标题】:How to handle encoding in Python 2.7 and SQLAlchemy ????‍☠️如何处理 Python 2.7 和 SQLAlchemy 中的编码????‍☠️
【发布时间】:2017-02-07 13:51:50
【问题描述】:

我在 Python 3.5 中编写了一段代码,其中我使用 Tweepy 和 SQLAlchemy 以及以下几行将推文加载到数据库中,并且效果很好:

twitter = Twitter(str(tweet.user.name).encode('utf8'), str(tweet.text).encode('utf8'))
session.add(twitter)
session.commit()

现在在 Python 2.7 中使用相同的代码会引发错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in 位置 139:序数不在范围内(128)

解决办法是什么?我的 MySQL 配置如下:

服务器端 --> utf8mb4 编码

客户端 --> create_engine('mysql+pymysql://abc:def@abc/def', encoding='utf8', convert_unicode=True)):

更新

似乎没有没有解决方案,至少 Python 2.7 + SQLAlchemy 没有。这是我目前发现的,如果我错了,请纠正我。

Tweepy,至少在 Python 2.7 中,返回 unicode 类型的对象。

在 Python 2.7 中:tweet = u'☠'<'unicode' type>

在 Python 3.5 中:tweet = u'☠'<'str' class>

这意味着如果我执行str(tweet),Python 2.7 会给我一个“UnicodeEncodeError”,因为 Python 2.7 会尝试将此字符“☠”编码为 ASCII,这是不可能的,因为 ASCII 只能处理 this basic characters

结论:

在 SQLAlchemy 行中仅使用此语句 tweet.user.name 会出现以下错误:

UnicodeEncodeError:“latin-1”编解码器无法对字符进行编码 位置 0-4:序数不在范围内(256)

在 SQLAlchemy 行中使用此语句 tweet.user.name.encode('utf-8')str(tweet.user.name.encode('utf-8')) 实际上应该以正确的方式工作,但它在数据库端显示未编码的字符:

ð´ââ ï¸Jack Sparrow

这就是我希望它显示的内容:

打印:????‍☠️ Jack Sparrow

特殊字符 unicode:u'\U0001f3f4\u200d\u2620\ufe0f'

特殊字符 UTF-8 编码:'\xf0\x9f\x8f\xb4\xe2\x80\x8d\xe2\x98\xa0\xef\xb8\x8f'

【问题讨论】:

  • 错字: 是代码点 \u2620

标签: python mysql unicode encoding utf-8


【解决方案1】:

不要使用任何编码/解码功能;他们只会使问题更加复杂。

请将连接设置为 UTF-8。
请将列/表设置为 utf8mb4 而不是 utf8。
请在 Python 代码的开头使用# -*- coding: utf-8 -*-

更多 Python tips 请注意,其中包含指向“Python 2.7 问题;Python 3 中的改进”的链接。

【讨论】:

  • 这:# -*- coding: utf-8 -*- 只是一个注释,只是一个约定,还是它会给代码带来任何价值?
  • # -*- coding: utf-8 -*- 告诉解释器在解析文件时使用哪种编码,它只影响包含非 ascii 字符(文字)的文件。它不会以任何其他方式影响代码。另外,请查看mysql unicode section of the sqlalchemy doc,您需要将?charset=... 添加到您的连接网址以更改连接字符集
猜你喜欢
  • 2016-04-24
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多