아이마이미

alembic 으로 플러그인들 데이터베이스 관리

안녕하세요.

 

g5도 여러가지로 잘쓰다가 g6 제가 좋아하는 언어로 작업이 된걸 보고 잠깐 보다가

데이터베이스 마이그레이션 기능이 없는듯 하여 찾다 보니 alembic 란게 있더군요

 

데이터 베이스와 models 를 비교 해서 데이터 베이스를 관리하기 편합니다.

g6의 기본 테이블 들과 약간의 문제로 연동이 어려울수 있는데 어제 쫌 고민 하다 방법을 찾아 

공유 하고자 글을 쓰네요 더좋은 방법도 있으시면 말 해주세요. 잠깐 본거라 어설프니 양해 바랍니다.

 

1. requirements.txt 마지막줄에 alembic==1.13.2 추가 후 pip 재인스톨

2. alembic.ini # sqlalchemy.url = driver://user:pass@localhost/dbname 주석 처리

3. alembic/env.py

import os

from dotenv import load_dotenv

load_dotenv()

 

config.set_main_option(

    "sqlalchemy.url",

    "mysql+pymysql://{username}:{password}@{host}:{port}/{db_name}".format(

        username=os.getenv('DB_USER'),

        password=os.getenv('DB_PASSWORD'),

        host=os.getenv('DB_HOST'),

        port=os.getenv('DB_PORT'),

        db_name=os.getenv('DB_NAME')

    )

)

 

from core.models import Base

import os

import sys

from sqlalchemy import MetaData

 

import os, sys

import importlib

# 현재 폴더의 위치를 가져옵니다.

current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# plugins 폴더 내의 모든 models 폴더를 찾습니다.

plugins_dir = os.path.join(current_dir, 'plugin')

 

from core.models import Base

 

for root, dirs, files in os.walk(plugins_dir):

    if "models.py" in files:

        # models.py 파일의 경로를 만듭니다.

        models_path = os.path.join(root, "models.py")

       

        # 폴더 이름을 가져옵니다.

        folder_name = os.path.basename(root)

       

        # 동적으로 models.py 파일을 import 합니다.

        spec = importlib.util.spec_from_file_location(folder_name, models_path)

        module = importlib.util.module_from_spec(spec)

        spec.loader.exec_module(module)

       

        # 폴더 이름을 합쳐서 Base를 새로운 이름으로 가져옵니다.

        if hasattr(module, 'Base'):

            new_name = f"{folder_name}Base"

            # `globals()`에 `new_name`을 키로 하고, `Base` 클래스를 값으로 저장합니다.

            globals()[new_name] = getattr(module, 'Base')

 

target_metadata = Base.metadata

 

# 문제가 되던 기존 g6 기본 또는 자동 g6 models에 존재 안하는 테이블들 떄문에 동기화 무시 입니다. 다른 것들도 추가 할수 있습니다.

def include_object(object, name, type_, reflected, compare_to):

    if type_ == 'table' and name.startswith('g6_'):

        return False

    return True

 

    context.configure(

        url=url,

        target_metadata=target_metadata,

        literal_binds=True,

        dialect_opts={"paramstyle": "named"},

        include_object=include_object, # 이거 추가

    )

        context.configure(

            connection=connection, target_metadata=target_metadata,

            include_object=include_object, #이거 추가

        )

 

플러그인 core.database 가 경로 문제 때문에 아래를 models 에 추가 합니다.

import os

import sys

 

# 현재 폴더의 위치를 가져옵니다.

current_dir = os.path.dirname(os.path.abspath(__file__))

# 현재 폴더의 위치의 parent 위치를 가져옵니다.

parent_dir = os.path.dirname(current_dir)

# parent 위치의 parent 위치를 가져옵니다.

grandparent_dir = os.path.dirname(parent_dir)

# grandparent 위치의 models를 sys.path에 추가합니다.

sys.path.insert(0, grandparent_dir)

 

from core.settings import settings

from core.models import Base

 

DB_TABLE_PREFIX = "hanni_shop_"

G6_DB_TABLE_PREFIX = settings.DB_TABLE_PREFIX

 

이렇게 하면 플러그인의 테이블들을 쉽게 관리 할수 있습니다.

 

팁 아닌 팁이네요 수고들 하시고 맛프 하세요

|

댓글 1개

플러그인 내부에 models로 플러그인 관련 데이터베이스를 관리한후 위의 내용을 적용시키신거세요?

댓글을 작성하시려면 로그인이 필요합니다.

그누보드6 팁자료실

그누보드6, 파이썬에 대한 팁과 자료를 올려주세요. 그누보드6 실서비스를 위한 웹서버 설정

+
제목 글쓴이 날짜 조회
1개월 전 조회 143
10개월 전 조회 869
1년 전 조회 749
1년 전 조회 856
1년 전 조회 783
1년 전 조회 598
1년 전 조회 596
1년 전 조회 909
1년 전 조회 573
1년 전 조회 920
1년 전 조회 2,002
1년 전 조회 2,856
1년 전 조회 1,648
2년 전 조회 2,598
2년 전 조회 1,269
2년 전 조회 1,813
2년 전 조회 2,405
2년 전 조회 795
2년 전 조회 1,338
2년 전 조회 1,185
2년 전 조회 1,414
2년 전 조회 1,083
2년 전 조회 958
2년 전 조회 1,199
2년 전 조회 879
2년 전 조회 1,305
2년 전 조회 821
2년 전 조회 669
2년 전 조회 1,171
2년 전 조회 1,246