巳年じゃないけど Python やろうぜ(その 22・最終回)
すっかり忘れていましたが、Python ネタの締めにこれの話をすると約束していたので書いておきます。
WSGI による Apache HTTPD との連携
Python では WSGI(Web Server Gateway Interface) という、Web サーバーと Web アプリケーションを接続する標準化されたインターフェースを利用して Web アプリケーションを Web サーバー上で公開することができます。
Django には WSGI を利用してアプリケーションを公開するための仕組みがあらかじめ用意されているので、それほど特別なことをする必要はありません。
まずは Python 側で mod_wsgi をインストールします。Windows 機の場合はこちらで公開されているものを使うのが良いでしょう。お使いの Apache HTTPD のバージョンに合わせたものをインストールしましょう。
次に、httpd.conf に以下の部分を追加します。(project_forder)
の部分は django_test
プロジェクトを作ったフォルダに読み替えます。
LoadModule wsgi_module "C:/Python/3.6/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIScriptAlias /wsgi-scripts "(project_forder)/django_test/django_test/wsgi.py" WSGIPythonPath "(project_forder)/django_test" Alias /static/ "(project_forder)/django_test/static/" <Directory "(project_forder)/django_test/django_test"> <Files wsgi.py> Require all granted </Files> </Directory> <Directory "(project_forder)/django_test/static"> Require all granted </Directory>
基本的に WSGI による Apache HTTPD との連携はこれで良いのですが、Django においてはこのままだと CSS や JavaScript、各種画像ファイルなどのいわゆる「静的ファイル」が上手く読み込めません。そこで
> python manage.py collectstatic
を実行して静的ファイルを Apache が認識できるフォルダにまとめておきます。
Django 2.0 における変更点
昨年の 12 月に正式に Django 2.0 がリリースされました。大きな変更点としては Python 2 系のサポートを打ち切ったことでしょう。今後 Django は Python 3 系のみをサポートしていくことになります。
細かな変更点として、URL ルーティングが従前の正規表現を用いた書き方に加えて、よりシンプルな表記が可能になった(django.urls.path
)ようです。
from django.urls import path from django.views.generic import ListView, DetailView from .models import City app_name = 'major_city' urlpatterns = [ path( '', ListView.as_view( queryset=City.objects.select_related().all(), context_object_name='cities', template_name='major_city/list.html' ), name='index' ), path( '<int:pk>/', DetailView.as_view( model=City, context_object_name='city', template_name='major_city/detail.html' ), name='show' ), ]