python - Flask-SQLAlchemy+mysql 搜索返回编码错误?
黄舟
黄舟 2017-04-17 17:54:47
0
3
423

用Flask-SQLAlchemy+mysql插入中文,再查询返回时报错

UnicodeEncodeError: 'ascii' codec can't encode characters in position 44-46: ordinal not in range(128)

# -*- coding: utf-8 -*-
from flask import Flask
from sqlalchemy import create_engine
from flask.ext.sqlalchemy import SQLAlchemy
from datetime import datetime
from sqlalchemy.orm import scoped_session, sessionmaker
import config
import os  
basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = config.DB_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app,use_native_unicode='utf8')

class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True) 
    name = db.Column(db.String(64), unique=True)

    def __repr__(self):
        return '<Role %r>' % self.name
    
print(config.DB_URI)     
print(Role.query.all())


数据库status已经全部设置成utf8,表也是utf8 在role的表中已经有中文数据 但不知道如何是好,还是报错

用的是python3

mysql status:

error:

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
伊谢尔伦

import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')

Just add it! Python is so tricky

阿神

If there is no problem with the database, then try it

reload(sys)
sys.setdefaultencoding('utf8')
刘奇

You can also write at the beginning of the file

General py files can be processed like this:

_*_ coding: utf-8 _*_

Then

import sys
reload(sys)
sys.setdefaultencoding('utf8')
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!