こんにちは。この記事では、タイトルの通り、Azure SQL Databaseと接続するPython-DjangoアプリケーションをMicrosoft AzureのPaaSサービスであるAzure App Serviceにデプロイする手順について整理しています。
前編は、アプリの構成設定と、デプロイまでの手順を解説しましたが、後編では、前編で作成したアプリをベースに、実際にSQL Databaseからデータを取得して表示するようなアプリに進化させていきたいと思います。
Contents
前編:~デプロイするまで
SQL Database上にテーブルを構築
最初に、SQL Database上にテーブルを作成します。
Azure PortalからSQL Databaseへアクセスし、Tableを作成する以下のSQLを実行します。(テーブルの内容は、適当です)
CREATE TABLE Users (
UserId INT IDENTITY PRIMARY KEY,
UserName NVARCHAR(128) NOT NULL,
);
![](https://i0.wp.com/www.simpletraveler.jp/wp-content/uploads/2021/06/image-55.png?resize=728%2C325&ssl=1)
テーブルを作成した後は、サンプルレコードを追加しておきます。
## サンプルレコードの追加
INSERT INTO Users(UserName) VALUES ('SampleUser1');
INSERT INTO Users(UserName) VALUES ('SampleUser2');
![](https://i0.wp.com/www.simpletraveler.jp/wp-content/uploads/2021/06/image-56.png?resize=728%2C369&ssl=1)
これでデータベース側の前準備はいったん終わりました。
Djangoアプリケーションの改修
続いて、Djangoアプリ側の機能追加です。いかんせんDjango初挑戦だったので、分からないことだらけでしたが、このページがとても理解を助けてくれました・・!感謝!!
https://djangobrothers.com/tutorials/blog_app/first_app/
プロジェクト内に新しいアプリを作成
最初に、以下コマンドを実行し、プロジェクト中に新たなアプリを作成します。
python manage.py startapp userprofile
すると、プロジェクトフォルダ配下に”userprofile”という名前の新しいディレクトリができました。
![](https://i0.wp.com/www.simpletraveler.jp/wp-content/uploads/2021/06/image-57.png?resize=440%2C721&ssl=1)
続いて、settings.pyファイルに、いま作成した新たなアプリを登録するための設定を追加しておきます。INSTALLED_APPS設定の中に、”userprofile”を追記すればOKです。
![](https://i0.wp.com/www.simpletraveler.jp/wp-content/uploads/2021/06/image-58.png?resize=728%2C395&ssl=1)
新規アプリのView, URL設定
次に、userprofileアプリのトップページ用に、index.htmlファイルを作成します。
cd userprofile
mkdir templates
cd templates
mkdir userprofile
cd userprofile
type nul > index.html
なぜ上のようなややこしいディレクトリ構成に・・と思いましたが、上の参考URLのサイトに解説されています。
## index.html
<h1>プロフィールページ</h1>
<p>ここはプロフィールページです。</p>
続いて、新規アプリフォルダ配下のView.pyに、リクエスト受信時にindex.htmlを返すための関数を追加します。
## View.py
from django.shortcuts import render
# 追加
def index(request):
return render(request, 'userprofile/index.html')
次にURLの構成です。プロジェクトフォルダ直下のurls.pyファイルを以下のように編集します。
## urls.py
from django.contrib import admin
from django.urls import path, include ## IncludeのImportも追加
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('userprofile.urls')) ## 追加
]
その上で、新規アプリフォルダ配下にurls.pyファイルを新たに作成し、以下内容で編集します。
type nul > urls.py
from django.urls import path
from . import views
app_name = 'userprofile'
urlpatterns = [
path('', views.index, name='index'),
]
![](https://i0.wp.com/www.simpletraveler.jp/wp-content/uploads/2021/06/image-61.png?resize=728%2C509&ssl=1)
ここまでできたところで、ローカルでアプリ起動。
python manage.py runserver
![](https://i0.wp.com/www.simpletraveler.jp/wp-content/uploads/2021/06/image-62.png?resize=728%2C153&ssl=1)
想定通り、index.htmlの内容が表示されました!!
データベースの情報を取得して内容を表示する
アプリの土台ができたところで、いよいよデータベースの内容を取得して表示する機能の追加です。
こちらも、上に紹介したサイトの解説が大変役立ちました。
まずは、models.pyファイルを作成し、UsersテーブルのModelを定義します。
## userprofileアプリフォルダ直下で
type nul > models.py
## models.py
from django.db import models
class Users(models.Model):
UserId = models.IntegerField(primary_key=True)
UserName = models.CharField(blank=False, null=False, max_length=150)
class Meta:
managed = False
db_table = 'Users' ## テーブル名指定
def __str__(self):
return self.UserName
![](https://i0.wp.com/www.simpletraveler.jp/wp-content/uploads/2021/06/image-64.png?resize=728%2C463&ssl=1)
コードの編集が終わったら、makemigrations/migrateコマンドを実行し、モデルの構築を完了します。
## プロジェクトフォルダ直下で
python manage.py makemigrations
python manage.py migrate
## makemigrationの実行ログ
Migrations for 'userprofile':
userprofile\migrations## makemigrationの実行ログ
Migrations for 'userprofile':
userprofile\migrations\0001_initial.py
- Create model UserProfile
## migrateの実行ログ
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, userprofile
Running migrations:
Applying userprofile.0001_initial... OK
01_initial.py
- Create model UserProfile
## migrateの実行ログ
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, userprofile
Running migrations:
Applying userprofile.0001_initial... OK
これで、モデルを使用する準備ができました!
続いで、このモデルを表示するためにView.pyを以下のように変更します。
## View.py
from django.shortcuts import render
from .models import Users ## 追加
# Create your views here.
def index(request):
userProfiles = Users.objects ## 追加
return render(request, 'userprofile/index.html', {'userProfiles':userProfiles}) ## 変更
そして、index.htmlの中身も以下のように変更します。
## index.html
<h1>プロフィールページ</h1>
<p>ここはプロフィールページです。</p>
{{ userProfiles }} ## 追加
これで最低限必要なコードはすべてかきました!ローカルでテストします。
python manage.py runserver
![](https://i0.wp.com/www.simpletraveler.jp/wp-content/uploads/2021/06/image-65.png?resize=717%2C206&ssl=1)
よし!Azure SQL Databaseからデータを取得して表示できています!!
このままAzureへデプロイ!App ServiceのURLにアクセスすると・・・
![](https://i0.wp.com/www.simpletraveler.jp/wp-content/uploads/2021/06/image-66.png?resize=728%2C178&ssl=1)
出ました!Azure上でも問題なくSQL DBへ接続してデータを取得できていますね!
簡単なサンプルアプリではありますが、これでシリーズ完結です!笑
最後までご覧いただき、ありがとうございました!
今回の記事が少しでも役に立った!という方は、ぜひ下のイイネボタンを押していただけると励みになります!また、記事へのフィードバックがありましたら、コメントもお待ちしております!