为什么SQLAlchemy create_engine与charset = utf8返回python类型<str>而不是键入<unicode>?

ksl*_*net 5 python mysql unicode sqlalchemy utf-8

使用Python 2.7和SQLAlchemy 0.7,我使用以下命令连接到MySQL DB:

engine = create_engine('mysql://username:password@host/dbname?charset=utf8',echo=False)
Run Code Online (Sandbox Code Playgroud)

根据SQLAlchemy文档,设置charset = utf8会自动隐含use_unicode = 1,因此所有字符串都应该以unicode形式返回. http://docs.sqlalchemy.org/en/rel_0_7/dialects/mysql.html专门给出了这个例子

#set client encoding to utf8; 所有字符串都以unicode create_engine('mysql + mysqldb:/// mydb?charset = utf8')的形式返回

那么,为什么当我在映射类中查询文本字段时,该字段最终是否为"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))
Run Code Online (Sandbox Code Playgroud)

输出是

 <type 'str'>
Run Code Online (Sandbox Code Playgroud)

如果我只是接受这个并在使用之前对字符串进行解码,那么事情就好了.但我不明白为什么上面的代码没有返回类型'unicode'.有人可以请解释一下吗?

ksl*_*net 4

当我发现我成功运行多次的不同脚本不再工作时,终于找到了答案。

我已将数据库中的排序规则从 utf8_general_ci 更改为 utf8_bin。MySQLdb 1.2.3 中存在一个错误,导致 utf8_bin 字符串无法被识别为文本,因此无法进行 unicode 转换。此问题已在 MySQLdb 1.2.4 中修复。

https://sourceforge.net/p/mysql-python/bugs/289/