DjangoでBatchを実行できるようにする

DjangoとMySQLを接続する

まずはMySQLで専用のDBをつくる.

CREATE DATABASE app_name;

settings.pyは以下のように書いた.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'app_name',
        'USER': 'username',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': 3306,
    }
}

最後にmigrateすると, app_name/models.pyがDBに反映される.

python manage.py migrate

コチラのサイトが参考になった.
code-database.com

django_boostを使ってテンプレートでPythonの組み込み関数を使えるようにする

インストール
sudo pip install django_boost
準備

INSTALLED_APPに登録

# project/settings.py
INSTALLED_APPS = [
...
'django_boost',
]

migratation

python manage.py migrate 
使い方

templateのhtmlファイルに{% load boost %}と記載

staticファイルが見つからないエラーが出る

アプリをproject/settings.pyに登録する必要がある.
アプリ名がsample_appとすると、次のように加えればおk.

INSTALLED_APPS = [
....
'sample_app'
]

バッチ作成・登録

アプリケーションで以下のようなコマンドでバッチプログラムを動かしたいとする。

python manage.py sample_batch

やり方は極めて簡単

まず、アプリケーション下にmanagement/commandsディレクトリを作成する。
次に、実行したいバッチ名と同じ名前のpythonファイルを作成する。

mkdir -p app/management/commands
vim app/management/commands/sample_batch.py
from django.core.management.base import BaseCommand
from db.models import Post
import sqlite3

class Command(BaseCommand):
    # [python manage.py help sample_batch]で表示されるメッセージ
    help = 'sample_batch'

    def add_arguments(self, parser):
        # コマンドライン引数を指定
        pass

    def handle(self, *args, **options):
        try:
            print('start batch')
            # 直でDB作業したい場合
            # con = sqlite3.connect('db.sqlite3')
            # cur = con.cursor()
            # query = 'SELECT * FROM db_post';
            # res = cur.execute(query)

            # ORM使う場合
            # posts = Post.objects.all()
            # print(posts)

            print('sample')
			
        except Exception as e:
            print(e)

処理内容はhandle()に書く。
実行結果は以下のようになる。

python manage.py sample_batch
sample

docs.djangoproject.com