aboutsummaryrefslogtreecommitdiff
path: root/qc_app/db_utils.py
blob: 98f8332d16bc241c25eb66828a4ece037d986ff7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
"""module contains all db related stuff"""
from typing import Tuple, Optional

from urllib.parse import urlparse
import MySQLdb as mdb
from flask import current_app as app

def parse_db_url(db_url) -> Tuple:
    """
    Parse SQL_URI configuration variable.
    """
    parsed_db = urlparse(db_url)
    return (parsed_db.hostname, parsed_db.username,
            parsed_db.password, parsed_db.path[1:], parsed_db.port)


def database_connection(db_url: Optional[str] = None) -> mdb.Connection:
    """function to create db connector"""
    host, user, passwd, db_name, db_port = parse_db_url(
        db_url or app.config["SQL_URI"])
    return mdb.connect(host, user, passwd, db_name, port=(db_port or 3306))