Home > Software design >  Configuration handling in Flask for MySQL database connection
Configuration handling in Flask for MySQL database connection

Time:01-03

I am new to Flask and currently exploring the official tutorial available in https://flask.palletsprojects.com/en/2.0.x/tutorial/factory/.

The example creates a blog based on a SQLite database. The database is defined in the following statement:

app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

Program Code

flaskr/__init__.py
import os

from flask import Flask


def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # a simple page that says hello
    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    return app

However, instead of am SQLite database, I want to use a MySQL database for storing information. How can I define the MySQL configuration at this stage?

I have modified the following code in the db.py file of the tutorial:

https://flask.palletsprojects.com/en/2.0.x/tutorial/database/

import mysql.connector
import click
from flask import current_app, g
from flask.cli import with_appcontext

# Function to create a database connection.
def get_db():
    if 'db' not in g:
        g.db=mysql.connector.connect(host="localhost",user="dbuser",password="database123",database="testdb")
    return g.db

# Function to close an existing database connection.
def close_db(e=None):
    db=g.pop('db',None)
    if db is not None:
        db.close()

# Function to initialize the database from a script.
def init_db():
    db = get_db()
    with open('schema.sql', 'r') as f:
        with db.cursor() as cursor:
            cursor.execute(f.read(), multi=True)
        db.commit()

@click.command('init-db')
@with_appcontext
def init_db_command():
    # Delete existing data and re-create tables.
    init_db()
    click.echo('Initialized the database.')

# Register with the application.
def init_app(app):
    app.teardown_appcontext(close_db)
    app.cli.add_command(init_db_command)

Can someone please provide some guidance on how to setup a MySQL database connection?

CodePudding user response:

Here you can use pymysql to manage your connections. Below is an example showing that how you can manage the DB connection.

import pymysql


def db_connect():
    conn = pymysql.connect(user='Your user',
                           password="Your password",
                           host="Your host",
                           database="Your database",
                           cursorclass=pymysql.cursors.DictCursor)
    return conn


def db_close(conn):
    if conn and conn.open:
        conn.close()


class DatabaseHandler(object):
    def __init__(self):
        self.conn = None

    def __enter__(self):
        self.conn = db_connect()
        return self.conn

    def __exit__(self, exc_type, exc_val, exc_tb):
        db_close(self.conn) 

You can use it as,

with DatabaseHandler() as db_conn:
     Any database operation with db_conn

CodePudding user response:

I did some digging around and figured that it is not mandatory to define the MySQL database connection inside the factory function for the application to work. I removed the database parameter values from app.config.from_mapping and only kept the database connection string inside the actual db.py file. So far, the application has been working fine.

app=Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(SECRET_KEY='development',)
  • Related