tatsunode
11/6/2017 - 11:49 AM

AWS EC2 Apache + RDS Postgresqlで(geo)djangoで動かすまで

AWS EC2 Apache + RDS Postgresqlで(geo)djangoで動かすまで

ubuntu server

インスタンスの作成. キーの取得.*.pem

RDSでDBの作成

postgresqlを利用(postgisのため) セキュリティグループの設定に注意.ポート5432空けておく. アクセスして"create extension postgis;"を実行.

[local] $ psql --host=hgoehoge.abcdefghi.ap-northeast-1.rds.amazonaws.com \
--port=5432 \
--username *** \
--dbname=*****
Password for user ***:

Ubuntuへのアクセス

[local] $ ssh -i *.pem ubuntu@{address}
$ uname --a
Linux ip------generic #118-Ubuntu SMP Thu Dec 17 22:52:10 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
$  cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.3 LTS"

必要なパッケージのインストール

postgresql, postgis

$ sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt trusty-pgdg main" >> /etc/apt/sources.list'
$ wget --quiet -O - http://apt.postgresql.org/pub/repos/apt/ACCC4CF8.asc | sudo apt-key add -
$ sudo apt-get update
$ sudo apt-get install postgresql-9.3-postgis-2.1 postgresql-contrib

django(geodjango)

$ sudo apt-get install gdal-bin
$ sudo apt-get install python-psycopg2
$ sudo apt-get install python-pip
$ sudo pip install Django

apache, mod_wsgi

$ sudo apt-get install apache2 apache2-dev
$ sudo apt-get instal libapache2-mod-wsgi

djangoまわり

プロジェクトの作成

$ django-admin startproject myproject
$ cd myproject
$ python manage.py startapp api

djangoの設定

DATABASES = {
  'default': {
  'ENGINE': 'django.contrib.gis.db.backends.postgis',
  'NAME': 'geodjangodb',
  'HOST': '++++++'  # DBアドレス
  'USER': '----',   # 前回作成DBユーザの名前
  'PASSWORD': '*****', # 前回作成DBユーザのパスワード
  }
}
INSTALLED_APPS = (
     ....
  'django.contrib.gis', 
  'api',
)

LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'

api/admin.py

django-leafletをインストールしておくと管理画面で 空間データがleaftlet上で表示されるようになる.

$ pip install django-leaflet

from django.contrib.gis import admin
from demo.models import Building
from leaflet.admin import LeafletGeoAdmin

admin.site.register(Building, LeafletGeoAdmin)

urls.py

from django.conf.urls import patterns, include, url
from django.contrib.gis import admin
admin.autodiscover()

urlpatterns = patterns('',
  url(r'^admin/', include(admin.site.urls)),
)

Apacheの設定・mod_wsgiの設定

confファイルを作成する. /etc/apache2/conf-enabled/以下などにhttp.confを作成

$ sudo vim /etc/apache2/conf-enabled/http.conf
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias / /home/ubuntu/wifibigdatalogger_server/wifibigdatalogger_server/wsgi.py
WSGIPythonPath /home/ubuntu/wifibigdatalogger_server
Alias /static/admin /usr/local/lib/python2.7/dis-packages/django/contrib/admin/static/admin/

<Directory /home/ubuntu/wifibigdatalogger_server/wifibigdatalogger_server>
<Files wsgi.py>
Requre all granted
</Files>
</Directory>

<Directory /usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin>
Require all granted
</Directory>

Apache restart

$ sudo /etc/init.d/apache2 restart