[SQLAlchemy] Table Drop, Create (+ flask, SQLite, SQLAlchemy 참고 코드)

깨미·2021년 12월 21일
0

All

db.drop_all()
db.create_all()

One

tablename.__table__.drop(db.engine)
tablename.__table__.create(db.engine)

Example Code

Define SQLAlchemy

flask_scripts를 사용하여 모듈 밖에서 스크립트를 관리할 때 사용하기 위해 staticmethod로 선언하여 사용한다.

flask_scripts 사용은 여기에서 확인할 수 있다.

# database.py

from flask_sqlalchemy import SQLAlchemy

class SQLiteAlchemy(SQLAlchemy):
    def apply_driver_hacks(self, app, info, options):
        options.update({
            'isolation_level': 'READ UNCOMMITTED',
        })
        super(SQLiteAlchemy, self).apply_driver_hacks(app, info, options)


class DBManager:
    db = None

    @staticmethod
    def init(app):
        db = SQLiteAlchemy(app)
        DBManager.db = db

    @staticmethod
    def init_db():
        db = DBManager.db
        db.drop_all()#all table drop, create
        db.create_all()

    @staticmethod
    def clear_db():
        DBManager.db.drop_all()
        
    @staticmethod
    def one_db():  #one table drop, create
        from backend_model.table_config import Example
        db = DBManager.db
        Example.__table__.drop(db.engine)
        Example.__table__.create(db.engine)

Define Table Class

#table_config.py
from backend_model.database import DBManager
db = DBManager.db
class Example(db.Model):
    __tablename__ = 'example'
    id = db.Column('id', db.Integer, primary_key=True)

Define SQLite DB URI


#appConfig.py
class DevelopmentConfig(CommonConfig):
    SQLALCHEMY_DATABASE_URI = 'sqlite:///./example.db'\

Flask Init

#__init__.py
from flask import Flask
from server_configuration.appConfig import *
from backend_model.database import DBManager

app = Flask()
app.config.from_object(DevelopmentConfig)


DBManager.init_db()
DBManager.one_db()

@app.route("/", methods=["GET"])
def page_index():
    resp = make_response(render_template("index.html"))
    return resp

Run App

#main.py
from backend import app
if __name__ == "__main__":
    app.run()

Excute

python main.py
profile
vis ta vie

0개의 댓글