为什么具有charset = utf8的SQLAlchemy create_engine返回python类型< str>而不输入< unicode> ;? [英] Why does SQLAlchemy create_engine with charset=utf8 return python type <str> and not type <unicode>?
问题描述
使用Python 2.7和SQLAlchemy 0.7,我使用以下命令连接到MySQL数据库:
Using Python 2.7 and SQLAlchemy 0.7, I'm connecting to a MySQL DB with the command:
engine = create_engine('mysql://username:password@host/dbname?charset=utf8',echo=False)
根据SQLAlchemy文档,设置charset = utf8会自动暗示use_unicode = 1,因此所有字符串都应以unicode的形式返回.专门 http://docs.sqlalchemy.org/en/rel_0_7/dialects/mysql.html 给出了例子
According to the SQLAlchemy docs, setting charset=utf8 automatically implies use_unicode=1, so that all strings should come back as unicode. http://docs.sqlalchemy.org/en/rel_0_7/dialects/mysql.html specifically gives the example
#将客户端编码设置为utf8;所有字符串都以unicode的形式返回 create_engine('mysql + mysqldb:///mydb?charset = utf8')
#set client encoding to utf8; all strings come back as unicode create_engine('mysql+mysqldb:///mydb?charset=utf8')
那么,为什么在查询映射类中的文本字段时,该字段的结尾类型为"str"?
So why, then, when I query a text field in a mapped class, does that field end up with type "str"?
Base = declarative_base(engine)
class RegionTranslation(Base):
''''''
__tablename__ = 'RegionTranslation'
__table_args__ = {'autoload':True}
def __init__(self, region_id, lang_id, name):
self.region_id = region_id
self.lang_id = lang_id
self.name = name
rtrans = session.query(RegionTranslation).filter_by(region_id = 1, lang_id = 6).one()
print (type(rtrans.name))
输出为
<type 'str'>
如果我只接受它并在使用它之前对字符串进行解码,那么一切都很好.但是我不明白为什么上面的代码没有返回类型'unicode'.有人可以请解释一下吗?
If I just accept this and decode the string before using it, things are fine. But I don't get why the above code isn't returning the type 'unicode'. Can someone please, please explain this?
推荐答案
当发现我已经成功运行多次的另一个脚本不再起作用时,终于找到了答案.
Finally found the answer when discovering that a different script I'd run successfully many times was no longer working.
我已将数据库中的排序规则从utf8_general_ci更改为utf8_bin. MySQLdb 1.2.3中存在一个错误,该错误导致utf8_bin字符串无法识别为文本,因此不会进行Unicode转换.这已在MySQLdb 1.2.4中修复.
I had changed the collation in my database from utf8_general_ci to utf8_bin. There is a bug in MySQLdb 1.2.3 that causes utf8_bin strings not to be recognized as text, so the unicode conversion isn't happening. This was fixed in MySQLdb 1.2.4.
https://sourceforge.net/p/mysql-python/bugs/289 /
这篇关于为什么具有charset = utf8的SQLAlchemy create_engine返回python类型< str>而不输入< unicode> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!