見出し画像

DjangoでSnowflakeに接続してみた

分析屋の下滝です。

業務で、djangoからSnowflakeに接続する必要が出ましたので、メモとして共有します。

分析用のDBとしてSnowflakeを使うのではなくアプリケーションとして使うようなケースなので、どれだけそのようなケースがあるのかは不明です。

Snowflakeへのdjangoコネクタが公式に存在しますので、それを使うことになります。

公式のチュートリアルもあります。

この記事では、チュートリアルがちょっと長いので参考にしながら簡潔に説明していきます。

django-snowflakeでsnowlfakeに接続する

Anacondaでも何でも良いので適当なpython環境を用意します。今回は、3.10を使います。

djangoをインストールします。

pip install django

インストールされたdjangoのバージョンを確認します。

python -m django --version
4.2.6

4.2に対応するdjango-snowflakeをインストールします。

>pip install django-snowflake==4.2.*
ERROR: Could not find a version that satisfies the requirement django-snowflake==4.2.* (from versions: 3.2a1, 3.2a2, 3.2b1, 4.0a1, 4.0b1, 4.1a1, 4.1b1, 4.2a1, 4.2b1)
ERROR: No matching distribution found for django-snowflake==4.2.*

4.2b1が最新のようなのでインストールします。

pip install django-snowflake==4.2b1

適当にsnowflakeにデータベースを作ります。ここではDJANGO_TESTというデータベースを作りました。

ウェアハウスも用意しておきます。ここでは「XS」という名前のXSサイズのウェアハウスを使います。


続いて、何でも良いのですが、今回は、djangoのチュートリアルをもとにプロジェクトを作ります。djangoに慣れている人はsettings.pyの箇所までスキップしてください。

プロジェクトを作ります。

django-admin startproject mysite

作ったmysiteフォルダに移動して、アプリを作ります。

python manage.py startapp polls

polls/views.pyを修正します。

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

polls/urls.pyを作ります。

from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="index"),
]

mysite/urls.pyを修正します。

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("polls/", include("polls.urls")),
    path("admin/", admin.site.urls),
]

settings.pyを修正します。"polls.apps.PollsConfig",を追加します。

INSTALLED_APPS = [
"polls.apps.PollsConfig",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]

ここからsnowlfake関連の話になります。

DATABASESの箇所をsnowflakeの設定に変えます。USER、PASSWORD、ACCOUNTは適切なものを設定してください。

DATABASES = {
    'default': {
        'ENGINE': 'django_snowflake',
        'NAME': 'DJANGO_TEST',
        'SCHEMA': 'PUBLIC',
        'WAREHOUSE': 'XS',
        'USER': 'YOUR_USERNAME',
        'PASSWORD': 'YOUR_PASSWORD',
        'ACCOUNT': 'YOUR_ACCOUNT_IDENTIFIER',
        # Include 'OPTIONS' if you need to specify any other
        # snowflake.connector.connect() parameters.
        # https://docs.snowflake.com/en/user-guide/python-connector-api.html#connect
        'OPTIONS': {},
    }
}

models.pyを修正します。

from django.db import models

# Create your models here.

class Product(models.Model):
    name = models.CharField(max_length=200)

マイグレーションして、DBにテーブルを作ります。

>python manage.py makemigrations polls
Migrations for 'polls':
  polls\migrations\0001_initial.py
    - Create model Product
>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying polls.0001_initial... OK
Applying sessions.0001_initial... OK

snowflake上に一連のテーブルが作られました。

作られたProductテーブルにレコードを作成してみます。views.pyを修正します。


def index(request):

    Product.objects.create(name="aaaa")
    Product.objects.create(name="bbbb")
    Product.objects.create(name="cccc")

    return HttpResponse("Hello, world. You're at the polls index.")

runして、djangoを起動します。

python manage.py runserver

http://127.0.0.1:8000/polls/
にアクセスします。

レコードが作られました。

モデルに対するその他の操作は通常と同じ用に使えると思います。ただ、いくつかの制約がありそうなので、ドキュメントを参照してください。

今回は以上です。

株式会社分析屋について

ホームページはこちら。

noteでの会社紹介記事はこちら。

専用の採用ページはこちら。

【データ分析で日本を豊かに】
分析屋はシステム分野・ライフサイエンス分野・マーケティング分野の知見を生かし、多種多様な分野の企業様のデータ分析のご支援をさせていただいております。 「あなたの問題解決をする」をモットーに、お客様の抱える課題にあわせた解析・分析手法を用いて、問題解決へのお手伝いをいたします!
【マーケティング】
マーケティング戦略上の目的に向けて、各種のデータ統合及び加工ならびにPDCAサイクル運用全般を支援や高度なデータ分析技術により複雑な課題解決に向けての分析サービスを提供いたします。
【システム】
アプリケーション開発やデータベース構築、WEBサイト構築、運用保守業務などお客様の問題やご要望に沿ってご支援いたします。
【ライフサイエンス】
機械学習や各種アルゴリズムなどの解析アルゴリズム開発サービスを提供いたします。過去には医療系のバイタルデータを扱った解析が主でしたが、今後はそれらで培った経験・技術を工業など他の分野の企業様の問題解決にも役立てていく方針です。
【SES】
SESサービスも行っております。