init_sqlalchemy.py 1.39 KB
Newer Older
Weizhi Cui's avatar
Weizhi Cui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#!/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
15
from sqlalchemy import text
Weizhi Cui's avatar
Weizhi Cui committed
16

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

db = SQLAlchemy()


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

    :param app: flask.Flask application instance
    :return: None
    """
崔为之's avatar
崔为之 committed
29
    cfg = app.config.Database
崔为之's avatar
崔为之 committed
30
    uri = DatabaseUri(
崔为之's avatar
崔为之 committed
31 32 33 34 35 36 37 38 39
        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())
崔为之's avatar
崔为之 committed
40
    db.app = app
Weizhi Cui's avatar
Weizhi Cui committed
41
    db.init_app(app)
崔为之's avatar
崔为之 committed
42
    with app.app_context():
崔为之's avatar
崔为之 committed
43 44
        db.session.execute(text(f"""
        CREATE TABLE IF NOT EXISTS {cfg.TableName} (
崔为之's avatar
崔为之 committed
45 46 47 48 49 50 51 52 53 54
            id SERIAL NOT NULL,
            username VARCHAR(80) NOT NULL,
            email VARCHAR(120) NOT NULL,
            password VARCHAR(255) NOT NULL,
            active BOOLEAN,
            created_at TIMESTAMP WITH TIME ZONE NOT NULL,
            PRIMARY KEY (id, created_at)
        ) PARTITION BY RANGE (created_at);
        """))
        db.session.commit()