13

我有一个带有 Unicode 列的 SQLAlchemy 模型。我有时会在其中插入 unicode 值(u'Value'),但有时也会插入 ASCII 字符串。解决此问题的最佳方法是什么?当我插入带有特殊字符的 ASCII 字符串时,我收到以下警告:

SAWarning: Unicode type received non-unicode bind param value ...

我该如何避免这种情况?插入不同类型字符串的正确方法是什么?

4

2 回答 2

5

有几种选择:

  1. 使用 禁用所有 SQLAlchemy 警告warnings.simplefilter('ignore', sqlalchemy.exc.SAWarning)
  2. 仅通过模块和 lineno 或消息使用更具体的过滤器规范禁用此警告,例如warnings.filterwarnings('ignore', '^Unicode type received non-unicode bind param value', sqlalchemy.exc.SAWarning).
  3. 使用String(convert_unicode=True)而不是Unicode类型。
  4. 重新考虑问题并更改代码以使用 unicode,即使是 ASCII 字符串。
于 2011-04-21T12:20:57.633 回答
0

您应该这样定义表类和构造函数:

class User(declarative_base()):
    _tablename__ = 'user'
    name = Column(Unicode(200, convert_unicode=False))
    textfield = Column(UnicodeText(convert_unicode=False))

user = Table('user', MetaData(),
Column('name', Unicode(200, convert_unicode=False), nullable=False),
Column('textfield', UnicodeText(convert_unicode=False), nullable=False),
)

当然,你不应该忘记URI+"charset=utf8"附加create_engine function

于 2013-09-06T06:14:40.540 回答