Python 向SQLAlchemy Unicode列插入字符串的正确方法
我有一个带有Unicode列的SQLAlchemy模型。我有时会在其中插入unicode值(u'Value'),但有时也会插入ASCII字符串。最好的办法是什么?当我插入带有特殊字符的ASCII字符串时,我收到以下警告:Python 向SQLAlchemy Unicode列插入字符串的正确方法,python,unicode,sqlalchemy,insertion,Python,Unicode,Sqlalchemy,Insertion,我有一个带有Unicode列的SQLAlchemy模型。我有时会在其中插入unicode值(u'Value'),但有时也会插入ASCII字符串。最好的办法是什么?当我插入带有特殊字符的ASCII字符串时,我收到以下警告: SAWarning: Unicode type received non-unicode bind param value ... 我如何避免这种情况?插入不同类型字符串的正确方法是什么?有几个选项: 使用warnings.simplefilter('ignore',SQLA
SAWarning: Unicode type received non-unicode bind param value ...
我如何避免这种情况?插入不同类型字符串的正确方法是什么?有几个选项:
warnings.simplefilter('ignore',SQLAlchemy.exc.SAWarning)
禁用所有SQLAlchemy警告警告。筛选器警告('ignore','^Unicode类型接收到非Unicode绑定参数值',sqlalchemy.exc.SAWarning)
String(convert\u unicode=True)
而不是unicode
类型您应该定义表类和构造函数,如下所示:
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”
,您尝试删除问题而不是解决它。关于第3点:sqlalchemy的官方文档
说使用Unicode类型
,但您说使用字符串(转换为Unicode=True)
,我也有同样的问题,但我不认为sqlalchemy可以解决禁用警告
,因为它有干净的代码
而不是脏的
。