1

Using SqlAlchemy, I have some String column that fails with

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 356: ordinal not in range(128)

because they are not Unicode.

I know that by doing my_string.decode('cp1252'), it works, but is it possible to define a method that will decode all the string returned from the database automatically.

With it, calling my_model.my_string, would be processed before return and decoded.

I looked into http://docs.sqlalchemy.org/en/rel_0_8/core/types.html#coercing-encoded-strings-to-unicode, which seems to be exactly what I'm looking for, but I don't know where to tell SqlAlchemy to use the CoerceUTF8 class.

4
  • Why does flask matter? Why not the DBMS you are using? Commented Aug 23, 2013 at 15:31
  • 1
    Why not have the DB-API adapter decode strings according to the connection charset? Commented Aug 23, 2013 at 15:44
  • You already found the solution. What you build there is a new type. So instead of Column(String...) or Column(Unicode...) you do Column(CoercedString...). Commented Aug 23, 2013 at 16:01
  • I forogt to mention that I tried to specify the UTF-8 charset in the connection string for the database, without luck. Turn out, the problem was my database encoding wasn't uft8. @Javex, post it as the answer, I'll accept it. Thanks for your comments guys :) Commented Aug 25, 2013 at 19:40

1 Answer 1

2

You already found the solution. What you build there is a new type. So instead of Column(String...) or Column(Unicode...) you do Column(CoercedString...).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.