init_sqlalchemy.py 962 Bytes
Newer Older
Weizhi Cui's avatar
Weizhi Cui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version     : Python 3.11.4
# @Software    : Sublime Text 4
# @Author      : StudentCWZ
# @Email       : StudentCWZ@outlook.com
# @Date        : 2023/10/28 22:01
# @File        : init_sqlalchemy.py
# @Description :
"""

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

崔为之's avatar
崔为之 committed
16
from application.utils import DatabaseURI
Weizhi Cui's avatar
Weizhi Cui committed
17 18 19 20 21 22 23 24 25 26 27

db = SQLAlchemy()


def init_database(app: Flask) -> None:
    """
    Initialize the database extension

    :param app: flask.Flask application instance
    :return: None
    """
崔为之's avatar
崔为之 committed
28 29 30 31 32 33 34 35 36 37 38 39 40
    cfg = app.config.get('Database')
    if cfg is None:
        raise KeyError('Key Database error')
    uri = DatabaseURI(
        db_type=cfg.Type,
        username=cfg.Username,
        password=cfg.Password,
        host=cfg.Host,
        port=cfg.Port,
        db=cfg.DB,
        driver=cfg.Driver,
    )
    app.config.setdefault('SQLALCHEMY_DATABASE_URI', uri.create())
Weizhi Cui's avatar
Weizhi Cui committed
41
    db.init_app(app)