Flask-SQLAlchemy:如何插入和查询utf8字符串?

时间:2016-04-22 15:35:49

标签: python python-2.7 sqlite sqlalchemy flask-sqlalchemy

我尝试使用Flask-SQLAlchemy将阿拉伯语单词插入数据库,但我发现了错误。

我正在做的是:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sqlite3.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(120), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

db.create_all()
test = Basic_Settings("مرحباً", "admin@gmail.com")
db.session.add(test)
db.session.commit()

所以我得到了这个错误:

sqlalchemy.exc.ProgrammingError: (sqlite3.ProgrammingError) You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings. [SQL: u'INSERT INTO user (username, email) VALUES (?, ?)'] [parameters: ('\xd9\x85\xd8\xb1\xd8\xad\xd8\xa8\xd8\xa7\xd9\x8b', 'admin@gmail.com')]

然后我r编辑我的代码并将utf-8设置为这样的阿拉伯语单词:

test = User("مرحباً".decode("utf-8"), "admin@gmail.com")

所以现在终端没有显示任何错误

之后我需要查询这些数据并将其写入文件,或者我想定义这些数据,所以我将其添加到我的代码中:

all = User.query.all()
f = open("utf-8.txt", "w")
f.write([x.username for x in all])
f.close()

现在我收到了这个错误:

TypeError: expected a string or other character buffer object

有没有办法解决这个问题,我不想把它写到文件中我想要定义它:

username2 = [x.username for x in all]

没有任何错误。

0 个答案:

没有答案