• Skip to main content
  • Skip to primary sidebar

学習記録

Djangoデプロイ

2020年7月29日 by 河副 太智 Leave a Comment

Contents

  • 1 indexページの作成
    • 1.1 Django_app/urls.py
    • 1.2 hello/views.py
    • 1.3 hello/urls.py
    • 1.4 Django_app/setting.py
    • 1.5 /etc/nginx/nginx.conf
    • 1.6 /etc/nginx/nginx.conf

indexページの作成

とりあえず簡単にindexページが表示されるだけのdjangoアプリをデプロイする。

プロジェクトを”Django_app”
アプリを”hello”で作成

Django_app/urls.py

1
2
3
4
5
6
7
8
9
10
from django.contrib import admin
from django.urls import path,include
import hello.views as hello
 
 
urlpatterns = [
    path("", hello.index, name="index"),
    path('admin/', admin.site.urls),
    path('hello/', include('hello.urls')),
]

hello/views.py

1
2
3
4
5
6
7
8
9
from django.shortcuts import render
from django.http import HttpResponse
 
 
def index(request):
    return HttpResponse("indexページ")
 
def top(request):
    return HttpResponse("Helloトップ")

hello/urls.py

1
2
3
4
5
6
from django.urls import path
from . import views
 
urlpatterns = [
    path('', views.top, name='top'),
]

Django_app/setting.py

一旦データベースの設定は全てコメントアウトする。
ロガーの出力先のフォルダはmkdirで作る

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import os
 
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$k@0dyh#ccb=(@s161+#b*oxp3m)%4iy#7ym*5l@wd9b*c3gj_'
 
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
 
ALLOWED_HOSTS = ['(ここにIPアドレス)', 'localhost']
#localhostを一緒に入れればローカルでも動かせる
 
# Application definition
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
 
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
 
ROOT_URLCONF = 'django_app.urls'
 
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
 
WSGI_APPLICATION = 'django_app.wsgi.application'
 
 
# データベース設定
# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.postgresql_psycopg2',
#         'NAME': 'django_app',
#         'USER': os.environ.get('DB_USER'),
#         'PASSWORD': os.environ.get('DB_PASSWORD'),
#         'HOST': '',
#         'PORT': '',
#     }
# }
 
 
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
 
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
 
 
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
 
LANGUAGE_CODE = 'en-us'
 
TIME_ZONE = 'UTC'
 
USE_I18N = True
 
USE_L10N = True
 
USE_TZ = True
 
 
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
 
STATIC_URL = '/static/'
 
 
#  ロギング
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
 
    # ロガーの設定
    'loggers': {
        # Djangoが利用するロガー
        'django': {
            'handlers': ['file'],
            'level': 'INFO',
        },
        # diaryアプリケーションが利用するロガー
        'diary': {
            'handlers': ['file'],
            'level': 'INFO',
        },
    },
 
    # ハンドラの設定
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'django_app/logs/django.log'),
            'formatter': 'prod',
            'when': 'D',  # ログローテーション(新しいファイルへの切り替え)間隔の単位(D=日)
            'interval': 1,  # ログローテーション間隔(1日単位)
            'backupCount': 7,  # 保存しておくログファイル数
        },
    },
 
    # フォーマッタの設定
    'formatters': {
        'prod': {
            'format': '\t'.join([
                '%(asctime)s',
                '[%(levelname)s]',
                '%(pathname)s(Line:%(lineno)d)',
                '%(message)s'
            ])
        },
    }
}

/etc/nginx/nginx.conf

静的ファイルとメディアファイルはアプリケーションサーバーの負担を
減らす為にwebサーバーから返す事もできる。

現時点ではアプリケーションサーバーから静的ファイルを返しているが
webサーバーから返す場合は/usr/share/nginx/html/staticと
/usr/share/nginx/html/mediaフォルダを作成してsudo vi /etc/nginx/nginx.confで
コメントアウトしているlocation /staticとlocation /mediaを有効化する。

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
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/
 
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
 
# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
 
events {
    worker_connections 1024;
}
 
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
 
    access_log  /var/log/nginx/access.log  main;
 
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
 
    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
 
    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;
    server {
        listen       80;
        server_name  3.129.28.206;
        root         /usr/share/nginx/html;
 
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
 
        #location /static {
        #  alias /usr/share/nginx/html/static;
        #}
 
        #location /media {
        #  alias /usr/share/nginx/html/media;
        #}
 
        location / {
          proxy_set_header Host $http_host;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;

/etc/nginx/nginx.conf

コマンド”vi ~/.bash_profile”で内容を変更し”source ~/.bashrc”で更新する

1
2
3
4
5
6
7
8
9
10
11
# User specific environment and startup programs
 
PATH=$PATH:$HOME/.local/bin:$HOME/bin
 
export PATH
export DB_USER=******
export DB_PASSWORD=******
export DJANGO_SETTINGS_MODULE=django_app.settings
export ALLOWED_HOSTS=3.129.**.***
export AWS_SES_ACCESS_KEY_ID='AKI***UHEC5VDL******'
export AWS_SES_SECRET_ACCESS_KEY='VjVpxDDDu8**oSLkOXtlVENuKSQeBRp****'

 

 

このエントリーをはてなブックマークに追加

Tweet
[`yahoo` not found]
このエントリーを Google ブックマーク に追加
LinkedIn にシェア
LINEで送る


Filed Under: Django

Reader Interactions

コメントを残す コメントをキャンセル

メールアドレスが公開されることはありません。 ※ が付いている欄は必須項目です

Primary Sidebar

カテゴリー

  • AWS
  • Bootstrap
  • Dash
  • Django
  • flask
  • GIT(sourcetree)
  • Plotly/Dash
  • VPS
  • その他tool
  • ブログ
  • プログラミング
    • Bokeh
    • css
    • HoloViews
    • Jupyter
    • Numpy
    • Pandas
    • PosgreSQL
    • Python 基本
    • python3
      • webアプリ
    • python3解説
    • scikit-learn
    • scipy
    • vps
    • Wordpress
    • グラフ
    • コマンド
    • スクレイピング
    • チートシート
    • データクレンジング
    • ブロックチェーン
    • 作成実績
    • 時系列分析
    • 機械学習
      • 分析手法
      • 教師有り
    • 異常値検知
    • 自然言語処理
  • 一太郎
  • 数学
    • sympy
      • 対数関数(log)
      • 累乗根(n乗根)
    • 暗号学

Copyright © 2025 · Genesis Sample on Genesis Framework · WordPress · Log in