가상환경
python3 -m venv maroenv
WSGI란 Web Server Gateway Interface의 약자로, 웹서버와 웹어플리케이션이 어떤 방식으로 통신하는가에 관한 인터페이스를 의미, 이 WSGI 규격에 맞춘 코드를 실행해주는 프로그램이 uWSGI임.
이 외에 Gunicorn 같은 프로그램 또한 WSGI 규격 웹 애플리케이션을 배포할 때 쓰임
build-essential gcc
apt install uwsgi sudo apt-get install uwsgi-plugin-python3
서버 실행은 uwsgi 명령어를 통해 실행 가능하지만 간단한 스크립트를 만들어 실행해 보자.
/etc/init 디렉토리에 있는 선언적 구성 파일을 기반으로 실행한다
# simple uWSGI script description "uwsgi tiny instance" start on runlevel [2345] stop on runlevel [06] respawn exec uwsgi --master --processes 4 --die-on-term --socket :3031 --wsgi-file /var/www/myapp.wsgi
uWSGI는 여러가지 포맷(ini,xml, yaml, json)을 지원한다. uwsgi --ini http://uwsgi.it/configs/myapp.ini # HTTP uwsgi --xml - # standard input uwsgi --yaml fd://0 # file descriptor uwsgi --json 'exec://nc 192.168.11.2:33000' # arbitrary executable
.INI 파일은 많은 응용 프로그램에서 사용되는 사실상 표준 구성 형식이다. [section] key = value 쌍으로 구성된다. [uwsgi] socket = /tmp/uwsgi.sock socket = 127.0.0.1:8000 workers = 3 master = true 기본적으로 uWSGI는 [uwsgi] 섹션을 사용하지만 filename : section 구문과 함께 INI 파일을 로드하는 동안 다른 섹션 이름을 지정할 수 있다. uwsgi--ini myconf.ini:app1
uWSGI에서 가장 기본적인 형태의 로깅은 요청, 오류 및 정보 메시지를 stdout / stderr 으로 생성한다. 로그 리다이렉션의 가장 기본적인 형태는 --logto / --logto2 / --daemonize 옵션으로, 로그를 파일로 정할 수 있다. ./uwsgi -s :3031 -w simple_app --daemonize /tmp/mylog.log ./uwsgi -s :3031 -w simple_app --logto /tmp/mylog.log ./uwsgi -s :3031 -w simple_app --uid 1001 --gid 1002 --logto2 /tmp/mylog.log stdout / stderr 대신 파일에 기록하려면 --logto를 사용하거나 uWSGI, - daemonize를 동시에 데몬을 실행하면 된다.
로그 포맷
uWSGI에는 사용자 정의 요청 로그 라인을 작성하기 위한 --logformat 옵션이 있다. • %(uri) -> REQUEST_URI • %(method) -> REQUEST_METHOD • %(user) -> REMOTE_USER • %(addr) -> REMOTE_ADDR • %(host) -> HTTP_HOST • %(proto) -> SERVER_PROTOCOL • %(uagent) -> HTTP_USER_AGENT (starting from 1.4.5) • %(referer) -> HTTP_REFERER (starting from 1.4.5) 다음 로그 형식을 사용하면 코드 정의 logvars에 액세스 할 수 있다. uwsgi --logformat 'worker id = %(worker_id) for request "%(method) %(uri) %(proto)" test = %(foo)'
mod_wsgi의 목적은 Python WSGI 인터페이스를 지원하는 Python 응용 프로그램을 호스팅 할 수 있는 간 단한 ApacheModule을 구현하는 것이다. 이 모듈은 웹 호스팅 서비스에서 실행되는 고성능 운영 사이트뿐 만 아니라 고성능 프로덕션 웹 사이트 호스팅에도 사용하기에 적합하다. 지원 가능한 웹프레임워크 및 어플리케이션
# apt-get install apache2 # apt-get install libapache2-mod-wsgi-py3
WSGIScriptAlias /test_wsgi /var/www/html/test_wsgi.py
$ a2enconf wsgi $ systemctl restart apache2
# create new
def application(environ,start_response):
status = '200 OK'
html = '<html>\n' \
'<body>\n' \
'<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;">\n' \
'mod_wsgi Test Page\n' \
'</div>\n' \
'</body>\n' \
'</html>\n'
response_header = [('Content-type','text/html')]
start_response(status,response_header)
return [html]
웹브라우저에서 http://localhost/test_wsgi 접속하여 확인한다.
Django는 안전하고 유지 관리 가능한 웹 사이트를 신속하게 개발할 수 있는 고차원적인 Python 기반 웹 프레임워크이다. 경험이 풍부한 개발자들에 의해 구축된 장고(Django)는 웹 개발의 번거로움을 해소할 수 있도록 하기 위해 고안되었다. 자유롭고 개방적이며 활발한 커뮤니티를 보유하고 있으며, 우수한 문서 및 유료 지원을 위한 다양한 옵션을 갖추고 있다.
가상 작업환경인 virtualenv를 설치한다.
root@www:~# apt-get -y install python-virtualenv
ubuntu@www:~$ virtualenv venv # virtualenv 생성 ubuntu@www:~$ cd ~/venv ubuntu@www:~/venv$ source bin/activate (venv)ubuntu@www:~/venv$ pip install -U pip (venv)ubuntu@www:~/venv$ pip install django #django 설치
Ubuntu@www:~$ cd ~/venv Ubuntu@www:~/venv$ source bin/activate # create “testproject” (venv)ubuntu@www:~/venv$ django-admin startproject testproject (venv)ubuntu@www:~/venv$ cd testproject
# configure database (default is SQLite) (venv)ubuntu@www:~/venv/testproject$ python manage.py migrate # create admin user (venv)ubuntu@www:~/venv/testproject$ python manage.py createsuperuser
# start server venv)ubuntu@www:~/venv/testproject$ python manage.py runserver 0.0.0.0:8000
views.py 작성
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse def main(request): html = '<html>\n' \ '<body>\n' \ '<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;">\n' \ 'Django Test Page\n' \ '</div>\n' \ '</body>\n' \ '</html>\n' return HttpRestponse(html) # Create your views here.
"""testproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('test app.urls')), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^testapp/$', views.main, name='main'), ]
# add testapp like follows INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'testapp', #추가 )
Django Test page까지 확인했으면 이제 Apache mod_wsgi와 Django를 연동해본다. 연동을 위해 django.conf 파일을 생성하여 설정한다.
# create new
WSGIDaemonProcess test app python-path=/home/ubuntu/venv/testproject:/home/ubuntu/venv/lib/python2.7/site-packages
WSGIProcessGroup test app
WSGIScriptAlias /django /home/ubuntu/venv/testproject/wsgi.py
<Directory /home/ubuntu/venv/testproject>
Require all granted
</Directory>
root@www:~# a2enconf wsgi root@www:~# systemctl restart apache2