DB settings when using Django + SQLAlchemy + Alembic

Django's standard ORM can be speedy and you may want to use SQLAlchemy. However, SQLAlchemy migration isn't very cool either, so I'd like to use Alembic instead.

Since each is an independent module, each DB is set in a different way. SQLAlchemy and Alembic refer to Django's settings because it's a hassle to write them separately.

file organization

First, assume the following file structure.

myProject/ +--- manage.py
           +--- alembic/ ---+-- env.py
           |                +---other
           +--- alembic.ini
           +--- myProject/ -+-- settings.py
           |                +---other
           +--- myApp/ -----+-- models.py
                            +---other

Django settings

Leave this as is the standard setting method. I'm assuming you will use mysql.

settings.py


# Database
 
DATABASE_ENGINE = 'mysql'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'xxxx',      #Appropriate
        'USER': 'xxxx',      #Appropriate
        'PASSWORD': 'xxxx',  #Appropriate
        'HOST': 'xxxx',      #Appropriate
        'PORT': 'xxxx',      #Appropriate
        'OPTIONS': {},       #If necessary
    }
}
 
SQLALCHEMY_OPTIONS = {} #If you need to configure SQLAlchemy

SQLAlchemy settings

sqlalchemy needs to set DB when creating session. If you need to create a file called db.py in myProject / myProject and create a session, load this file so that you can create a session.

myProject/myProject/db.py


# -*- coding: utf-8 -*-
"""db session and util."""
 
from myProject import settings
 
import sqlalchemy.orm
 
from sqlalchemy.engine.url import URL
 
def db_url():
    db_settings = settings.DATABASES['default']
    url = URL(drivername=settings.DATABASE_ENGINE,
        database=db_settings['NAME'],
        username=db_settings['USER'],
        password=db_settings['PASSWORD'],
        host=db_settings['HOST'],
        port=db_settings['PORT'] or None,
        query = getattr(db_settings, 'OPTIONS', {})
        )
    return url
 
def create_engine():
    try:
        url = db_url()
    except:
        raise
    options = getattr(settings.DATABASES['default'], 'SQLALCHEMY_OPTIONS', {})
    engine = sqlalchemy.create_engine(url, **options)
    return engine
 
def make_session():
    Session = sqlalchemy.orm.sessionmaker(bind=create_engine())
    session = Session()
    return session

Alembic

Basically, alembic DB settings are set from alembic.ini. However, this is inconvenient as it is not referenced from the settings.py file as it is, so set it dynamically with alembic / env.py.

env.py


###Excerpt
import os
import sys
  
from alembic import context
  
#If this file is left as it is, settings cannot be read, so pass it through the path.
path = os.path.join(os.path.dirname(__file__), '../')
sys.path.append(path)
 
from user import models
from myProject.db import db_url
  
config = context.config
 
#Set URL
url = str(db_url())
config.set_main_option("sqlalchemy.url", url)

Recommended Posts

DB settings when using Django + SQLAlchemy + Alembic
DEBUG settings when using Django
SQLAlchemy + DB migration by Alembic
DB table insertion process using sqlalchemy
[Django] Settings for sending emails using postfix
django default settings
Settings when using Jupyter Notebook under Proxy server
Proxy settings when using pip or Jupyter Notebook
Django + MySQL settings
Django URL settings
Summary when using Fabric
Try using Django templates.html
Django command completion settings
Precautions when using Chainer
Notes on using Alembic
Eliminate errors that occur when using Django REST Swagger with Django 3.0
How to resolve CSRF Protection when using AngularJS with Django