I encountered this error:
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)
This happens when Im trying to save an ORM object with the assigned Python unicode string. And as a result, dict parameters has a unicode string as one of its values ββand causes an error when enforcing str .
I tried to set convert_unicode=True setting on the engine and column, but to no avail.
So what is a good way to handle unicode in SQLAlchemy?
UPDATE
Here are some details about my setup:
Table:
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 Model:
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 installs:
ENGINE = create_engine('postgresql://me: secret@localhost /my_db', encoding='utf8', convert_unicode=True) Session = sessionmaker(bind=ENGINE)
And the code that creates the error simply creates a session, creates a Document object and saves it with the source with unicode` strign field assigned to it.
UPDATE # 2
Check out this repo - it has automated the configuration of Vagrant / Ansible and reproduces this error.