WSGI (Web Server Gateway Interface) は PSGI に影響を与えた python の標準化された Web インターフェースです。
WSGI の実装としては上記二つの選択肢があります。前者は Apache に依存しており更新も活発ではないため、後者の uwsgi を利用します。
必須ではありませんが、今回は pyenv/virtualenv を用いて 2.7.10 をシステムインストールした状況を想定します。
$ pyenv shell 2.7.10
$ pyenv exec pip install uwsgi
$ pyenv exec pip install uwsgitop
wsgi.py
#!/bin/env python
# -*- coding: utf-8 -*-
import sys
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return ["Hello World, python version: \n%s\n" % (sys.version)]
wsgi.ini
[uwsgi]
http = :8080
stats = 127.0.0.1:8181
wsgi-file = wsgi.py
master = true
processes = 4
threads = 2
実行
$ pyenv exec uwsgi wsgi.ini
動作検証
$ ps auxw | grep wsgi
$ pyenv exec uwsgitop localhost:8181
$ curl http://localhost:8080/
/etc/uwsgi/vassals/wsgi-001.ini
[uwsgi]
http = :8080
stats = 127.0.0.1:8181
chdir = /usr/local/uwsgi/apps
wsgi-file = wsgi-001.py
master = true
processes = 4
threads = 2
logto = /var/log/uwsgi/wsgi-001.log
/usr/local/uwsgi/apps/wsgi-001.py
#!/bin/env python
# -*- coding: utf-8 -*-
import sys
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return ["Hello World, python version: \n%s\n" % (sys.version)]
/etc/uwsgi/emperor.ini
[uwsgi]
emperor = /etc/uwsgi/vassals
uid = nobody
gid = nobody
起動手順
$ sudo su -l
$ chown nobody: /var/log/uwsgi
$ cd /etc/uwsgi/
$ pyenv shell 2.7.10
$ pyenv exec uwsgi emperor.ini
/etc/nginx/nginx.conf
で uwsgi_pass
するためには /etc/uwsgi/vassals/wsgi-001.ini
において http
ではなく socket
を使用します。
/etc/nginx/nginx.conf
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
access_log /var/log/nginx/access.log combined;
server {
listen 80 default_server;
include uwsgi_params;
location / {
uwsgi_pass 127.0.0.1:8080;
}
location /001 {
uwsgi_pass 127.0.0.1:8080;
}
location /002 {
uwsgi_pass 127.0.0.1:9090;
}
}
}
/etc/uwsgi/vassals/wsgi-001.ini
[uwsgi]
socket = 127.0.0.1:8080
stats = 127.0.0.1:8181
chdir = /usr/local/uwsgi/apps
wsgi-file = wsgi-001.py
master = true
processes = 4
threads = 2
logto = /var/log/uwsgi/wsgi-001.log
/usr/local/uwsgi/apps/wsgi-001.py
#!/bin/env python
# -*- coding: utf-8 -*-
import sys
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return ["Hello World, python version: \n%s\n" % (sys.version)]
/etc/uwsgi/emperor.ini
[uwsgi]
emperor = /etc/uwsgi/vassals
uid = nobody
gid = nobody
起動手順
$ sudo su -l
$ chown nobody: /var/log/uwsgi
$ cd /etc/uwsgi/
$ pyenv shell 2.7.10
$ pyenv exec uwsgi emperor.ini
動作検証
$ ps auxw | grep wsgi
$ sudo less /var/log/uwsgi/wsgi-001.log
$ pyenv exec uwsgitop localhost:8181
$ curl http://localhost/