Flask_SQLAlchemy, MySQL, store Swedish characters å, ä, ö? Flask_SQLAlchemy, MySQL, store Swedish characters å, ä, ö? flask flask

Flask_SQLAlchemy, MySQL, store Swedish characters å, ä, ö?


Since you're using Python 2.7, you need to specify that your string contains unicode.

>>> db.session.add(Users(u'ä'))

You can also use a future import to treat all strings as unicode.

from __future__ import unicode_literals

Alternatively you can upgrade your version of Python. 2.7 is the last version to treat strings as bytes rather than unicode.

Edit

You'll also need to update your __repr__ so that it properly handles unicode.

def __repr__(self):    return self.name.decode('utf-8')

or whatever encoding you want to use.

In general, you'll need to make sure you handle encoding from and decoding to unicode. I can't urge you enough to consider using a more recent version of Python. One of the largest changes in Python 3 addresses this very issue.


In using UTF-8 characters, try to avoid any kind of encode/decode; that just masks the real problem, which is usually in the configuration somewhere.

My notes on sqlalchemy:

db_url = sqlalchemy.engine.url.URL(drivername='mysql', host=foo.db_host,    database=db_schema,    query={ 'read_default_file' : foo.db_config, 'charset': 'utf8' })json.dumps(mydict, ensure_ascii=False) avoids "\u...." strings.

https://docs.sqlalchemy.org/en/latest/dialects/mysql.html#mysql-unicode

Python 2.7 is rather old, see this about the differences with 3:

https://stackoverflow.com/a/40708131/1766831

Python tips for utf8: http://mysql.rjweb.org/doc.php/charcoll#python