4. 기본 정보
Version
• Ubuntu
• Django
• Apache
• MySQL
• Python
4
(ADP3)david@ubt-django:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 14.04.2 LTS
Release: 14.04
Codename: trusty
>>> import django
>>> django.get_version()
'1.8.2'
//2015-05-23 기준 최신
(ADP3)david@ubt-django:~$ apache2 -v
Server version: Apache/2.4.7 (Ubuntu)
Server built: Mar 10 2015 13:05:59
mysql> select version();
+-------------------------+
| version() |
+-------------------------+
| 5.5.43-0ubuntu0.14.04.1 |
+-------------------------+
(ADP3)david@ubt-django:~$ python
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
// Ununto 14.04.2에 Default로 설치되어 있음
- Web의 정보들 대부분은 Python2 Base로 되어 있다.
- Django의 정보는 아래에서.
https://docs.djangoproject.com/en/1.8/
- Django Project는 아래 책의 내용으로.
“Django로 배우는 쉽고 빠는 웹 개발 ‘파이썬 웹프로
그래밍’”
5. 기본 정보
가상 환경 구성
• “가상환경은 선택이 아닌 필수다” 라는 말이 있더라.
5
$ sudo apt-get python3-pip
$ pip3 install virtualenv
# Python3를 Main version으로 설정
$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 1
$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 2
$ sudo update-alternatives --config python
# 가상환경 적용
$ mkdir workspace
$ cd workspace/
$ virtualenv ADP3
Using base prefix '/usr'
New python executable in ADP3/bin/python3
Also creating executable in ADP3/bin/python
Installing setuptools, pip, wheel...done.
$ source ADP3/bin/activate
(ADP3)$ # activate 시키면 만든 이름이 Prompt에 계속 보인다.
(ADP3)$ deactivate # 가상환경 종료 명령
$ adp3
(ADP3)$ which python # (참고)가상환경에서 Python의 위치는?
/home/david/workspace/ADP3/bin/python
6. 설치 정보 -01
Django, Apache 설치
• Django는 가상환경 내에 설치되지만 Apache는 그렇지 않다.
6
$ pip3 install Django
$ apt-get install apache2
$ sudo vi /etc/apache2/apache2.conf # Apache 설치 후 AH00558 에러 제거
ServerName localhost # 맨 아래에 추가한다.
$ sudo apt-get install libapache2-mod-wsgi-py3 # Python3용 mod_wsgi 설치
7. 설치 정보-02
Django Project 만들기
• Sample Project 생성
7
$ pwd
/home/david/
$ mkdir webspace
$ cd webspace
$ djagno-admin.py startproject mysite
$ mv mysite ch3 # project 명은 변경해도 무관
$ tree
.
├── ch3
│ ├── manage.py
│ └── mysite
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── mywsgiserver.py
8. 설치 정보-03
Django Project의 Application 만들기
8
## 이 Tree를 기준으로 작업이 진행되며 앞으로 Path에 관련된 내용이 많지만,
## 개인 설정에 따라 Path 정보들을 바꿔주면 된다.
## 아래 Tree 내용 중 settings.py가 Apache 연동을 위해 수정되어야 할 파일이다.
## wsgi.py는 뭔가 손을 대 줘야 할 것 같지만 실제로는 자동 생성된 후 수정할 일이 없다.
## /etc/apache2/apache2.conf에서 wsgi.py를 참조하기 위해 다수의 설정을 해야 한다.
$ cd ch3/
$ python manage.py startapp polls
$ tree
.
├── manage.py
├── mysite
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-34.pyc
│ │ └── settings.cpython-34.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── polls
├── admin.py
├── __init__.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
9. 설치 정보-04
Django 기본 동작 확인
• 내장 서버 이용
• model, admin 수정 후 DB 적용하기
9
$ python manage.py runserver 0.0.0.0:8000
Performing system checks...
System check identified no issues (0 silenced).
May 27, 2015 - 18:12:10
Django version 1.8.2, using settings 'mysite.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
## 여기서 Django 내장 DB인 SQLite에 migration 하고, 나중에 MySQL로 다시 옮겨 갈 거다.
$ python manage.py makemigrations
Migrations for 'polls':
0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
10. 설치 정보-05
Deploy 하기 전 필요 작업
• 보안 등의 이유로 Deploy(배포) 전 해야 하는 작업 들
• https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
10
$ vi settings.py
## DEBUG = True에서 False로 변경
## ALLOWED_HOSTS = [] 에서 운용하는 서버 IP 또는 Domain 등록
DEBUG = False
ALLOWED_HOSTS = [ u'xx.xx.xx.xx'] # Server's IP or Domain Name
## static file 위치 조정
## Web에서는 Image JavaScript, CSS 등을 static file이라고 한다.
## Django는 이미 static file들의 위치를 알고 사용하고 있지만 상용 Web server를 연동할 때는
## 해당 Project에서 사용하는 파일들의 위치를 알려 줘야 하고 이 파일들을 Project directory로
## 가져와야 한다.
## 이런 작업을 '정적 파일 배포 작업' 이라고 한다.
STATIC_URL = '/static/'
## 아래의 한 줄을 추가해 준다.
## Static files의 기본 URL는 static/ 이며 이는 www_static으로 Aliasing 될 것이다.
STATIC_ROOT = os.path.join(BASE_DIR, "www_static")
11. 설치 정보 -06
Deploy 하기 전 필요 작업 - 계속
• https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
11
$ mkdir www_static
$ python manage.py collectstatic
You have requested to collect static files at the destination
location as specified in your settings:
/home/david/webspace/ch3/www_static
This will overwrite existing files!
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: yes
Copying '/home/david/workspace/ADP3/lib/python3.4/site-
packages/django/contrib/admin/static/admin/img/nav-bg-grabber.gif'
Copying '/home/david/workspace/ADP3/lib/python3.4/site-
packages/django/contrib/admin/static/admin/img/inline-restore.png'
Copying '/home/david/workspace/ADP3/lib/python3.4/site-
packages/django/contrib/admin/static/admin/img/icon_clock.gif'
Copying '/home/david/workspace/ADP3/lib/python3.4/site-
packages/django/contrib/admin/static/admin/img/icon_addlink.gif'
Copying '/home/david/workspace/ADP3/lib/python3.4/site-
packages/django/contrib/admin/static/admin/img/default-bg-reverse.gif'
-- 생략 --
## 많은 파일들을 카피해 온다.
12. 설치 정보 -07
Deploy 하기 전 필요 작업 - 계속
• https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
12
## SQLite DB 권한 조정 for Apache
## MySQL로 변경 할 예정이니 패스해도 사실 상관 없지만, MySQL 연동 전에 뭔가를 확인하고 싶으면 필요하다.
$ pwd
/home/david/webspace/ch3
$ mkdir db
$ mv db.sqlite3
$ mv db.sqlite3 db/
$ chmod 777 db
$ chmod 666 db/db.sqlite3
$ vi mysite/setting.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db/db.sqlite3'),
## db.sqlite3 --> db/db.sqlite3 으로 변경했음
}
}
13. 설치 정보 -08
Apache와 mod_wsgi 연동
• /etc/apache2/apaceh2.conf 수정하기
13
## mod_wsgi와 Apache 서버와의 연동은 '내장모드(기본)'와 '데몬모드' 두 가지를 이용 할 수 있다.
## Django에서는 Daemon mode 사용을 추천한다.
## https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/modwsgi/
$ sudo vi /etc/apache2/apache2.conf
### 아래의 내용을 무조건 맨 아래에 추가한다.
WSGIScriptAlias / /home/david/webspace/ch3/mysite/wsgi.py
# mod_wsgi will be used by "Daemon-mode"
WSGIDaemonProcess mysite python-
path=/home/david/webspace/ch3/:/home/david/workspace/ADP3/lib/python3.4/site-packages
## Project를 위해 만들어진 Python module들이 불러질 Path를 정의하는 것이며, virtualenv 환경인 경우
site-packages 경로를 추가한다.
WSGIProcessGroup mysite
<Directory /home/david/webspace/ch3/mysite> # # wsgi.py의 위치 정보 및 권한 부여
<Files wsgi.py>
Require all granted
</Files>
</Directory>
Alias /static/ /home/david/webspace/ch3/www_static/ ## static files 위치 Alias
<Directory /home/david/webspace/ch3/www_static/> ## static files 권한 부여
Require all granted
</Directory>
14. 설치 정보 -09
Apache와 mod_wsgi 연동 - 계속
14
# Apache 연동 확인
+++++++++++++++++++++++++++++++++++++
$ sudo service apache2 restart
## 만들어진 Application의 Page를 Port 8000이 아니라 Default인 80(HTTP)으로 열어 보는 것이다.
## 즉, Web Browser에서 http://xxx.xxx.xxx.xxx:8000 이 아니라 http://xxx.xxxx.xxxx.xxx 으로
## 연결을 해 보는 거다. 잘 열리면 OK.
※ 참고
# 앞서 WSGI 관련 설정을 /etc/apache2/apache2.conf에 작성했다.
# Apache2는 기본적으로 Virtual Host가 동적하고 있다. (한 서버에서 다수의 Domain을 사용할 수 있다.)
# 이때, default site는 /etc/apache2/site-available/000-default.conf 에 설정된 내용에 따라 동작하며,
# 이 Site를 운용할 때 a2ensite 000-default.conf 명령을 수행해서 Enable 해 준다.
# Enable 된 Site는 /etc/apache2/site-enabled/에 Symbolic Link 되어 있다.
# 그래서 Django Apache2 연동을 위해 apaceh2.conf에 작성한 내용들은 000-default.conf의
# <VirtualHost *:80><?VirtuaHost> 사이에 작성해 놓거나 다른 포트를 쓸 때는 해당 포트로 작성하면 된다.
# 아니면 Virtual Host로 직접 돌리면 된다.
15. 설치 정보 -10
MySQL 설치
• MySQL 및 Python용 MySQL Connector를 설치하고 Django에서 사
용할 DB 및 User를 생성해 준다.
15
$ sudo apt-get install mysql-server mysql-client ## server, client 설치
$ sudo apt-get install libapache2-mod-auth-mysql ## mysql 사용자 인증 모듈
## 아래의 설치가 없으면 Python3에서 MySQLDB module을 사용할 수 없다.
## Python3용 MySQL Connector라고 부른다.
## http://stackoverflow.com/questions/4960048/python-3-and-mysql
## https://pypi.python.org/pypi/mysqlclient
$ sudo apt-get install python-dev libmysqlclient-dev
$ sudo apt-get install python3-dev libmysqlclient-dev
$ pip3 install mysqlclient ## MySQL Connector [Django에서 추천하는 Library]
$ mysql -u root -p
Password: ********
mysql> create database mysite;
mysql> grant all privileges on mysite* to 'django'@'localhost' identified by 'django123'
16. 설치 정보 -11
MySQL 연동을 위해 setting.py 설정하기
• SQLite 설정 대신 MySQL로 설정을 추가한다.
16
$ vi settings.py
## SQLite을 사용했던 설정을 Comment 처리 또는 삭제
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db/db.sqlite3'),
# }
#}
## 아래 내용 추가
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysite',
'USER': 'django',
'PASSWORD': 'django123',
'HOST': '127.0.0.1',
'PORT': '',
}
}
17. 설치 정보 -12
기존 DB를 MySQL로 Migration하기
Django Admin User 생성하고 Apache 재 시작
17
$ python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: staticfiles, messages
Apply all migrations: auth, contenttypes, polls, admin, sessions
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying polls.0001_initial... OK
## SQLite DB에 만들어져 있었으므로 새로 추가한다.
## 그런데 들어가보면 Tabel은 있으나 추가했던 Field의 내용들은 없다.(해 보면 안다.)
## 다시 채워야 한다. Project 처음부터 MySQL로 시작하는 것이 좋겠다.
$ python manage.py createsuperuser
Username (leave blank to use 'david'):
Email address: david@modonet.kr
Password:
Password (again):
Superuser created successfully.
$ sudo service /etc/apache2/apache2.conf
18. 설치 정보 -13
기존 DB를 MySQL로 Migration하기
18
# Django Admin에서 Field를 다시 채워 넣고 mysql에
서 확인
+++++++++++++++++++++++++++++++++++++
mysql> show tables; ## Table은 Migrate 된 것이
고,
+----------------------------+
| Tables_in_mysite |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
| polls_choice |
| polls_question |
+----------------------------+
12 rows in set (0.00 sec)
mysql> select * from polls_choice; ## Field는 다시
채운 것이다.
+----+--------------------+-------+-------------+
| id | choice_text | votes | question_id |
+----+--------------------+-------+-------------+
| 1 | Reading | 1 | 1 |
| 2 | Soccer | 0 | 1 |
| 3 | Climibing | 0 | 1 |
| 4 | Jessica Simpson | 0 | 2 |
| 5 | Scarlett Johansson | 0 | 2 |
| 10 | Lee, Hyolee | 1 | 2 |
| 11 | Kim, Taehee | 0 | 2 |
| 12 | Seoul | 0 | 3 |
| 13 | Seongnam | 1 | 3 |
| 14 | Anyang | 1 | 3 |
+----+--------------------+-------+-------------+
10 rows in set (0.00 sec)