PythonのフレームワークであるDjangoでアプリケーション作成にチャレンジしています。
実践的なJavascriptやCSSの実装を踏まえて本当に基本的な部分ですが
内容として、jQuery,jQueryUIはCDNから、CSS,jQueryのJavascriptファイルを静的フォルダー(/static)からの読み込みました
また、CentOS7とNginxにGunicornを利用して構築していますが、Gunicornの起動は systemdを利用しています。
content/Webアプリケーションの環境構築
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30  | 
						// user:django を作成し「sudo」の実行権限を付与しています。 // myserver に djangoでログインしています。 // venvによる 仮想環境 py37 (python Ver3.7.4)が登録済みとします。 // 仮想環境に移動 [django@sakura2 ~]$ source py37/bin/activate (py37) [django@myserver ~]$ python -V Python 3.7.4 // 環境を構築します。  (py37) [django@myserver ~]$ mkdir content (py37) [django@myserver ~]$ cd contnt (py37) [django@myserver ~]$ django-admin startproject content . (py37) [django@myserver ~]$ django-admin startapp webapps (py37) [django@myserver ~]$ tree . |-- content |   |-- __init__.py |   |-- settings.py |   |-- urls.py |   `-- wsgi.py |-- manage.py `-- webapps     |-- __init__.py     |-- admin.py     |-- apps.py     |-- migrations     |   `-- __init__.py     |-- models.py     |-- tests.py     `-- views.py  | 
					
content/settigs.pyの編集
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23  | 
						// settings.pyの編集 // 公開するアプリケションのアドレス名称登録 // 「 https://learning.codingstock.jp 」で公開 ALLOWED_HOSTS = ['learning.codingstock.jp'] INSTALLED_APPS = [     'webapps.apps.WebappsConfig',  # 追加     'django.contrib.admin',     'django.contrib.auth',     'django.contrib.contenttypes',     'django.contrib.sessions',     'django.contrib.messages',     'django.contrib.staticfiles', ] // 日本語対応 LANGUAGE_CODE = 'ja' TIME_ZONE = 'Asia/Tokyo' // 画像やCSSを参照する際のSTATICファイル等々を配置する場所 // コマンドラインにてファイルを収集するために 「python manage.py collectstatic」 を実行する STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static')  | 
					
ルーティングファイル content/urls.pyの編集
| 
					 1 2 3 4 5 6 7 8 9 10  | 
						// content/urls.py の編集 from django.contrib import admin from django.urls import path, include urlpatterns = [     path('admin/', admin.site.urls),     path('webapps/', include('webapps.urls'))     path('', include('webapps.urls')),         # https://learning.codingstock.jp でもサイトに移動かの ]  | 
					
アプリケーションのルーティングファイル content/webapps/urls.pyの編集
| 
					 1 2 3 4 5 6 7 8  | 
						from django.urls import path from . import views app_name = 'webapps' urlpatterns = [     path('', views.index, name='index'),  # /webapps ]  | 
					
ビュー content/webapps/views.pyの設定
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13  | 
						from django.shortcuts import render, redirect import django import random def index(request):     context = {         'randam': random.random(),         'django_version': django.get_version(),         # その他、今回サンプルページで表示する状況を取得して index.html に渡します。         # ここでは内容を割愛します。     }     return render(request, 'webapps/index.html',context)     #    render() 関数は、第1引数として request オブジェクトを、第2引数としてテンプレート名を、第3引数(任意)として辞書を受け取ります。     #    テンプレートでレンダリングし、その HttpResponse オブジェクトを返します。  | 
					
テンプレートの設置
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23  | 
						(py37) [django@sakura2 webapps]$ tree . |-- __init__.py |-- __pycache__ |-- admin.py |-- apps.py |-- migrations |-- models.py |-- static |   `-- webapps |       |-- cssjs |       |   |-- scrypt.js |       |   `-- style.css |       `-- images |           |-- learningHead.jpg |           |-- logo-2.jpg |           `-- logo_footer.png |-- templates |   `-- webapps |       |-- base.html |       `-- index.html |-- tests.py |-- urls.py  | 
					
テンプレートタグ
{% %}はテンプレートタグで、Djangoに用意されている特別な動きをするタグです。
{% extends ‘webapps/base.html’ %}タグは親テンプレートとしてbase.htmlを継承することを意味しています。
スタティックなファイル(画像、CSS,javasciptファイル等々)は /static/ フォルダーに設置し読み込みます
setting.py で指定したフォルダーを指定しています。
今回の場合は以下にのように設定しています。
STATIC_URL = ‘/static/’
STATIC_ROOT = os.path.join(BASE_DIR, ‘static’)
静的ファイル(画像やCSS等々)は「static」フォルダーに設置しロードするときに利用します。
アプリフォルダーに配置したあと、コマンドラインで「python manage.py collectstatic」を実行します。
実際の読み込み
{% load static %}
<h1><img src=”{% static “webapps/images/logo-2.jpg” %}”>
base.html
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64  | 
						<!DOCTYPE html> <html lang="ja"> <head><meta charset="UTF-8"> <title>コーディングストック | Webアプリケーション、データベース、サーバー環境</title> <meta name="description" content="Webサイトデザイン、プログラミング、サーバー構築運用の記録"> <meta name="keywords" content="ネストクリニック,病院"> {% load static%} <link rel="stylesheet" href="{% static 'webapps/cssjs/style.css' %}?{{randam}}"  						type="text/css" media="screen"> # cssファイルは開発中は更新が著しいのでパラメーターに乱数をわたして毎回読み込ませるようにする。 <link href="https://fonts.googleapis.com/css?family=Anton rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <link rel="stylesheet"  	href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <script src="{% static "webapps/cssjs/scrypt.js" %}?{{randam}}"></script></head> # ジャバスクリプトファイルは開発中は更新が著しいのでパラメーターに乱数をわたして毎回読み込ませるようにする。 <body> <div id="dl" style="display:none;">   <p>ホームページの遷移</p> </div> <!-- #wrapper ここから -->	 	<div id="wrapper"> 		<!-- #header ここから -->	 		<header> 			<h1><img src="{% static "webapps/images/logo-2.jpg" %}" width=350 alt="コーディングストック"></h1>             <div class="cp_navi">             <ul>             	<li><a href="Home">Home</a></li>             	<li>             		<a href="Products">Products <span class="caret"></span></a>             		<div>             			<ul>             				<li><a href="programing">programing</a></li>             				<li><a href="design">design</a></li>             				<li><a href="server">server</a></li>             			</ul>             		</div>             	</li>             	<li><a href="Blog">Blog</a></li>             	<li><a href="About">About</a></li>             	<li><a href="Inquiry">Inquiry</a></li>             </ul>             </div> 		</header>		 		<!-- #header ここまで -->	         <!-- #wrapper ここから -->	         <div id="wrapper">         {%block content %}        #Django ブロックタグで各ページで継承して利用する。         {% endblock %} 	</div> <!-- #wrapper ここまで --> <!-- #footer ここから -->	 <footer> </footer> <!-- #footer ここまで -->	 </body> </html>  | 
					
index.html
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44  | 
						{% extends 'webapps/base.html' %} {%block content %} {% load static%} 		<img src="/static/webapps/images/learningHead.jpg" alt="コーディングストック"> 		<!-- #mainimage ここから -->	 		<div id="mainimage"> 		</div> 		<!-- #mainimage ここまで -->	 		<!-- #left ここから -->	 		<div id="left">     		<h2>動作環境</h2> <table id="django">    		 <tr><th>Package</th><th>Version</th></tr> <tr><td>Python</td><td>3.7.4 </td></tr>  <tr><td>Django</td><td>2.2.6 </td></tr>  <tr><td>djangorestframework</td><td>3.10.3</td></tr>  <tr><td>gunicorn</td><td>19.9.0</td></tr>  <tr><td>pip</td><td>19.2.3</td></tr>  <tr><td>pytz</td><td>2019.2</td></tr>  <tr><td>setuptools</td><td>40.8.0</td></tr>  <tr><td>sqlparse</td><td>0.3.0 </td></tr>  <tr><td>uWSGI</td><td>2.0.18</td></tr>  </table>        		 		</div> 		<!-- #left ここまで -->	 		<!-- #right ここから -->	 		<div id="right">     		<h2>Codingstock python リンク集</h2>     		<ul class="django">             <li><a href="https://www.codingstock.jp/centoos7-nginx-ssl-gunicorn-django/" target="_blank">centoOS7 + Nginx + SSL + Django インストールの記録</a></li>			             <li><a href="https://www.codingstock.jp/python-django-init/	" target="_blank">[python] Django ローカル環境にインストール サンプルアプリケーション を表示してみる。</a></li>			             <li><a href="https://www.codingstock.jp/centos-python3-mysql/" target="_blank">CentoOS7 python3 CGI Mysqlデータベースを扱う</a></li>			             <li><a href="https://www.codingstock.jp/centos7-python-cgi-rss/	" target="_blank">centos7 python3のインストール、RSSを取得、CGIでパースしてWeb で表示する</a></li>             <li><a href="https://www.codingstock.jp/python-anaconda-environment/" target="_blank">python Anacondaを利用した開発環境の整備 jupter Notebook のインストール</a></li>             <li><a href="https://www.codingstock.jp/mac-windows-python/" target="_blank">Mac Windows にpython の最新バージョンをインストール</a></li>     		</ul> 		</div> 		<!-- #right ここまで -->	 		<div id="clearfix"></div> {% endblock %}  | 
					
systemd の設定
| 
					 1 2 3 4 5 6 7 8 9 10 11  | 
						# /usr/lib/systemd/system/content.service を新規作成、編集します。 [Unit] Description=gunicorn daemon After=network.target [Service] WorkingDirectory=/home/django/content ExecStart=/xxxx/yyyyy/py37/bin/gunicorn --access-logfile - --bind 127.0.0.1:8001 content.wsgi:application [Install] WantedBy=multi-user.target  | 
					
systemd 起動、自動起動設定、登録の確認、ログ参照
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42  | 
						// 登録したサービースの開始 [root@sakura2 ~]# systemctl start content // サービスの自動起動有効 [root@sakura2 ~]# systemctl enable content Created symlink from /etc/systemd/system/multi-user.target.wants/content.service to /usr/lib/systemd/system/content.service. // サービス一覧から登録したサービスをgrepで検索 [root@sakura2 ~]# systemctl list-unit-files --type=service | grep content content.service                               enabled  // 起動したサービスの状態確認 [root@myserver ~]# systemctl status content * content.service - gunicorn daemon    Loaded: loaded (/usr/lib/systemd/system/content.service; enabled; vendor preset: disabled)    Active: active (running) since Thu 2019-10-10 02:26:29 JST; 2s ago  Main PID: 26716 (gunicorn)    CGroup: /system.slice/content.service            |-26716 /usr/local/bin/python3.7 /usr/local/bin/gunicorn --access-logfile - --bind 127.0.0.1:8001 content.wsgi:application            `-26719 /usr/local/bin/python3.7 /usr/local/bin/gunicorn --access-logfile - --bind 127.0.0.1:8001 content.wsgi:application Oct 10 02:26:29 myserver.mydomain.com systemd[1]: Started gunicorn daemon. Oct 10 02:26:29 myserver.mydomain.com gunicorn[26716]: [2019-10-10 02:26:29 +0900] [26716] [INFO] Starting gunicorn 19.9.0 Oct 10 02:26:29 myserver.mydomain.com gunicorn[26716]: [2019-10-10 02:26:29 +0900] [26716] [INFO] Listening at: http://127.0.0.1:8001 (26716) Oct 10 02:26:29 myserver.mydomain.com gunicorn[26716]: [2019-10-10 02:26:29 +0900] [26716] [INFO] Using worker: sync Oct 10 02:26:29 myserver.mydomain.com gunicorn[26716]: [2019-10-10 02:26:29 +0900] [26719] [INFO] Booting worker with pid: 26719 // ログの参照 [root@sakura2 ~]# systemctl status content * content.service - gunicorn daemon    Loaded: loaded (/usr/lib/systemd/system/content.service; enabled; vendor preset: disabled)    Active: active (running) since Thu 2019-10-10 02:45:24 JST; 3h 46min ago  Main PID: 27700 (gunicorn)    CGroup: /system.slice/content.service            |-27700 /usr/local/bin/python3.7 /usr/local/bin/gunicorn --access-logfile - --bind 127.0.0.1:8001 content.wsgi:application            `-27703 /usr/local/bin/python3.7 /usr/local/bin/gunicorn --access-logfile - --bind 127.0.0.1:8001 content.wsgi:application Oct 10 02:45:24 myserver.mydomain.com gunicorn[27700]: [2019-10-10 02:45:24 +0900] [27700] [INFO] Starting gunicorn 19.9.0 Oct 10 02:45:24 myserver.mydomain.com gunicorn[27700]: [2019-10-10 02:45:24 +0900] [27700] [INFO] Listening at: http://127.0.0.1:8001 (27700) // ログの確認で同様なフィルター [root@sakura2 ~]journalctl --unit=content  | 
					
参考サイト
Django 日本語ドキュメント
CentOS7でDjangoを動かすシリーズ
Gunicorn – WSGI server
nginx + gunicornでVPSにDjangoの環境構築
