我遇到过这样的错误:
File "/vagrant/env/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 435, in do_execute cursor.execute(statement, parameters) exceptions.UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 8410: ordinal not in range(128)
当我试图用指定的Python unicode
字符串保存ORM对象时,就会发生这种情况.因此dict
parameters
,将unicode字符串作为其值之一,并在将其强制转换为str
类型时产生错误.
我试图convert_unicode=True
设置引擎和列的设置,但没有成功.
那么在SQLAlchemy中处理unicode的好方法是什么?
这是关于我的设置的一些细节:
表:
Table "public.documents" Column | Type | Modifiers ------------+--------------------------+-------------------------------------------------------- id | integer | not null default nextval('documents_id_seq'::regclass) sha256 | text | not null url | text | source | text | not null downloaded | timestamp with time zone | not null tags | json | not null Indexes: "documents_pkey" PRIMARY KEY, btree (id) "documents_sha256_key" UNIQUE CONSTRAINT, btree (sha256)
ORM模型:
class Document(Base): __tablename__ = 'documents' id = Column(INTEGER, primary_key=True) sha256 = Column(TEXT(convert_unicode=True), nullable=False, unique=True) url = Column(TEXT(convert_unicode=True)) source = Column(TEXT(convert_unicode=True), nullable=False) downloaded = Column(DateTime(timezone=True), nullable=False) tags = Column(JSON, nullable=False)
SQLAlchemy设置:
ENGINE = create_engine('postgresql://me:secret@localhost/my_db', encoding='utf8', convert_unicode=True) Session = sessionmaker(bind=ENGINE)
产生错误的代码只是创建一个会话,实例化一个Document
对象并使用分配给它的source
字段with
unicode`trign保存它.
检查此 repo - 它具有自动Vagrant/Ansible设置,并重现此错误.