Search code examples
pythonmysqlflaskencodingemoji

Storing and displaying emojis with mysqldb and Python Flask


I have a database with a table called posts and I have two fields called title and description. Both title and description can contain emoji characters.

The solutions to similar problems told me to convert the character set to utf8mb4 and collate to utf8mb4_bin and also change the column type from text to NVARCHAR(255). I've even tried different combinations of using utf8, utf8mb4, utf8mb4_unicode_ci and utf8mb4_general_ci. They all don't work in displaying emojis.

error

Instead, this error will pop up once I try displaying the emojis. Anyone have a work around this?

I tried using different combinations of unicodes and collations to the database, but all don't seem to work.


Solution

  • I solved my problem. I had to make sure the charset connection and the collation connection was set to utf8mb4 and utf8mb4_unicode_ci respectively. I did this with the Flask-MySQLdb library.

    from flask_mysqldb import MySQL
    
    app = Flask(__name__)
    app.config['MYSQL_HOST'] = 'host'
    app.config['MYSQL_USER'] = 'user'
    app.config['MYSQL_PASSWORD'] = 'password'
    app.config['MYSQL_DB'] = 'db_name'
    app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
    app.config['MYSQL_CHARSET'] = 'utf8mb4'
    app.config['MYSQL_COLLATION'] = 'utf8mb4_unicode_ci'
    
    mysql = MySQL(app)