Search code examples
mysqlflaskpeeweepython-3.9

How do I connect to a remote MySQL db using Flask Application Factory and Peewee FlaskDB


I'm learning Flask and have been developing an app, and everything has been working fine while using a SQLite database. But, I'm not getting anywhere when attempting to connect to a remote MySQL server (with or without SSL).

Here's the __init__.py

import os
from flask import Flask
from peewee import *
from playhouse.flask_utils import FlaskDB
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail
from myapi.config import Config
from myapi.main.loggers import logger


db = FlaskDB()
bcrypt = Bcrypt()
login_manager = LoginManager()
login_manager.login_view = 'users.login'
login_manager.login_message_category = 'info'
mail = Mail()


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(Config)

    db.init_app(app)
    bcrypt.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)

    from myapi.users.routes import users
    from myapi.posts.routes import posts
    from myapi.main.routes import main
    from myapi.errors.handlers import errors

    app.register_blueprint(users)
    app.register_blueprint(posts)
    app.register_blueprint(main)
    app.register_blueprint(errors)

    logger.info('App has been created.')

    return app

The DATABASE config which does work:

    DATABASE = {
        'name': 'example.db',
        'engine': 'peewee.SqliteDatabase',
    }

The DATABASE config which I'd like to work (but for the life of me haven't been about to work out) is:

    DATABASE = {
        'name': 'mydb',
        'engine': 'peewee.MySQLDatabase',
        'user': 'root',
        'passwd': 'root',
        'host': 'xxx.xxx.xxx.xxx'}

The error I'm getting from python is:

peewee.ImproperlyConfigured: MySQL driver not installed!

I am able to connect to MySQL through MySQL Workbench and HeidiSQL, so I can't see the issue being there.

(Additionally, if anyone has any pointers on getting encryption up and running in the above scenario, that would be great!)


Solution

  • You need to ensure that the python mysql bindings are installed. Typically you will want to install pymysql:

    pip install pymysql