Flask_SQLAlchemy,MySQL,存储瑞典字符å,ä,ö?

时间:2016-11-20 18:36:40

标签: mysql flask flask-sqlalchemy mysql-python utf8mb4

我无法通过使用Flask_SQLAlchemy来修改MySQL中的瑞典字符:(我已经尝试找到一个星期的解决方案,我真的需要帮助,因为感觉我已经走到了死胡同。我认为它可能是我的工具在版本兼容性方面存在问题,但我不希望如此!我正在尝试使用Flask,Flask_SQLAlchemy和MySQL(5.5.3)构建一个网站。如果这是无法解决的,我正在考虑将Flask_SQLAlchemy更改为其他内容.. (我参加了一门编程课程(Python),剩下的就是自我思考,所以如果你能在答案中尽可能详细,我会非常高兴,非常感谢任何建议!)

(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:\>

以下是testAlchemy.py文件中的代码

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

db.create_all()
db.session.commit()

president1=Users('Obama')
president2=Users('Trump')
db.session.add(president1)
db.session.add(president2)
db.session.commit()

这应该是一些提示..

(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.
Please check out: http://continuum.io/thanks and https://anaconda.org
>>> from testAlchemy import Users, db
>>> db.session.add(Users('Federer'))
>>> db.session.commit()
>>> Users.query.all()
[Obama, Trump, Federer]
>>> db.session.add(Users('ä'))
>>> db.session.commit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\orm\scoping.py", line 157, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\orm\session.py", line 801, in commit
self.transaction.commit()
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\orm\session.py", line 392, in commit
self._prepare_impl()
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\orm\session.py", line 372, in _prepare_impl
self.session.flush()
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\orm\session.py", line 2019, in flush
self._flush(objects)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\orm\session.py", line 2137, in _flush
transaction.rollback(_capture_exception=True)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 60, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\orm\session.py", line 2101, in _flush
flush_context.execute()
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 373, in execute
rec.execute(self)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 532, in execute
uow
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\orm\persistence.py", line 174, in save_obj
mapper, table, insert)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\orm\persistence.py", line 800, in _emit_insert_statements
execute(statement, params)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\engine\base.py", line 914, in execute
return meth(self, multiparams, params)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\sql\elements.py", line 323, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\engine\base.py", line 1010, in _execute_clauseelement
compiled_sql, distilled_params
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\engine\base.py", line 1146, in _execute_context
context)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\engine\base.py", line 1341, in _handle_dbapi_exception
exc_info
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\util\compat.py", line 202, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\engine\base.py", line 1139, in _execute_context
context)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\sqlalchemy\engine\default.py", line 450, in do_execute
cursor.execute(statement, parameters)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\MySQLdb\cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "C:\Users\MyName\Anaconda3.1\envs\competeEnv\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (1366, "Incorrect string value: '\\x84' for column 'column_name' at row 1") [SQL: u'INSERT INTO users (column_name) VALUES (%s)'] [parameters: ('\x84',)]
>>>

2 个答案:

答案 0 :(得分:2)

由于您使用的是Python 2.7,因此您需要指定您的字符串包含unicode。

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

您还可以使用将来的导入将所有字符串视为unicode。

from __future__ import unicode_literals

或者,您可以升级您的Python版本。 2.7是将字符串视为字节而不是unicode的最后一个版本。

修改

您还需要更新__repr__以便正确处理unicode。

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

或您想要使用的任何编码。

通常,您需要确保处理unicode的编码和解码。我不能敦促你考虑使用更新版本的Python。 Python 3中最大的变化之一就是解决了这个问题。

答案 1 :(得分:0)

在使用UTF-8字符时,请尝试避免任何形式的编码/解码;只是掩盖了实际的问题,通常是在某个地方的配置中。

关于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较旧,请参见与3的区别:

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

utf8的Python技巧:http://mysql.rjweb.org/doc.php/charcoll#python