Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python with MySql "SAWarning: Unicode type received non-unicode bind param value" error

Before asking this question I've checked other posts on the similar. The answers provided simply suppressed the warning, instead of proposing a remedy.

I have a web application written with Python + Flask, which handles async requests sent with jquery in the unicode format. Content-Type:application/json; charset=UTF-8

Here is an example of the data sent from my web browser to the server. The data can be a mix of latin and non-latin characters. I've noticed that non-latin characters are codified but latin are not.

body: "Хочу Ñходить на #фильм Картель. ÐеÑÐ¼Ð¾Ñ‚Ñ€Ñ Ð½Ð° поÑредÑтвенные отзывы, фильм должен быть прикольным. Вот его опиÑание http://www.allocine.fr/film/fichefilm_gen_cfilm=202971.html"

Here is the definition of my MySqlAlchemy class

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Unicode(1024))

Now, when I try to submit the data to the database I receive the error below:

SAWarning: Unicode type received non-unicode bind para m value.
param.append(processorskey)

In between I'm using Flask-Restful component to handle HTTP requests:

class PostListApi(Resource):
    decorators = [login_required]
    def post(self):
        body=request.json['body']
        post = Post(body=body)
        db.session.add(post)
        db.session.commit()

The question is how should I handle the data correctly on the server side thus to make sure that non-unicode characters are not being written into the DB?

like image 752
Ryzhiy Kot Avatar asked Nov 20 '13 09:11

Ryzhiy Kot


1 Answers

You can simply force the body to unicode.

class PostListApi(Resource):
    decorators = [login_required]
    def post(self):
        body=request.json['body']
        post = Post(body=unicode(body))
        db.session.add(post)
        db.session.commit()
like image 162
doog abides Avatar answered Oct 12 '22 11:10

doog abides