I can't retrieve characters like ä and ê from MySQL by using Flask-SQLAlchemy. I am trying to build a website using Flask, Flask_SQLAlchemy and MySQL (5.5.3). I have taken one course in programming (Python) and the rest is self thought so I would be very happy if you could be as detailed as possible in your answers, very thankful for any advice!
This link was slightly helpful, but I have problems with retrieving not storing:
Flask_SQLAlchemy, MySQL, store Swedish characters å, ä, ö?
(competeEnv) C:\>conda list
# packages in environment at C:\Users\MyName\Anaconda3.1\envs\competeEnv:
#
click 6.6 py27_0
flask 0.11.1 py27_0
Flask-SQLAlchemy 2.1 <pip>
itsdangerous 0.24 py27_0
jinja2 2.8 py27_1
markupsafe 0.23 py27_2
mysql-python 1.2.5 py27_0
pip 9.0.1 py27_0
python 2.7.12 0
setuptools 27.2.0 py27_1
sqlalchemy 1.1.4 py27_0
vs2008_runtime 9.00.30729.1 2
werkzeug 0.11.11 py27_0
wheel 0.29.0 py27_0
(competeEnv) C:\>
Here is the code in testAlchemy.py file
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:myPassword@myServer/firstdb'
app.config['SQLALCHEMY_ECHO'] = False
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True
app.config['MYSQL_DATABASE_CHARSET'] = 'utf8mb4'
db = SQLAlchemy(app)
class Users(db.Model):
__tablename__='users'
id=db.Column('iduser', db.Integer, primary_key=True)
name=db.Column('column_name', db.String(193))
def __init__(self, name):
self.name=name
def __repr__(self):
return self.name.decode('utf-8')
db.create_all()
db.session.commit()
president1=Users('Obama')
president2=Users('Trump')
db.session.add(president1)
db.session.add(president2)
db.session.commit()
Here should be some hints..
(competeEnv) C:\Users\MyName\Anaconda3.1\envs>python
Python 2.7.12 |Continuum Analytics, Inc.| (default, Jun 29 2016, 11:07:13)[MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
>>> from testAlchemy import Users, db
>>> db.session.add(Users('Federer'))
>>> db.session.commit()
>>> Users.query.all()
[Obama, Trump, Federer]
>>> db.session.add(Users(u'ä'))
>>> db.session.commit()
>>> Users.query.all()
[Obama, Trump, Federer, Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "testAlchemy.py", line 23, in __repr__
return self.name.decode('utf-8')
File "C:\Users\MyName\Anaconda3.1\envs\envNew\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 0: ordinal not in range(128)
>>>