2018-07-16

Python CGI on Apache & FASTCGI on NginX

在Apache2上修改http.conf,讓Apache能以CGI執行python:
==============================================
...
LoadModule cgid_module modules/mod_cgid.so
...
<Directory "/opt/bitnami/apache2/htdocs">
...
Options FollowSymLinks MultiViews +ExecCGI
AddHandler cgi-script .py
...
</Directory>
==========================================================
若是使用bitnami LAMP stack,需再同時修改 conf/bitnami/bitnami.conf,修改設定同上
==========================================================

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

==========================================================
在NginX上修改nginx.conf,加入以下片段,以fast-cgi執行python:
==========================================================
location ~ \.py$ {
    root html;
    fastcgi_read_timeout 300;
    #fastcgi_pass 127.0.0.1:10240;
    fastcgi_pass unix:/tmp/python-fcgi.sock; #使用.sock監聽
    fastcgi_index index.py;
    fastcgi_param SCRIPT_FILENAME $request_filename;
    include fastcgi_params;
}
==========================================================
若是使用bitnami,可以新建一個 conf/bitnami/pythonfastcgi.conf,加入如上設定,並修改 conf/bitnami.conf,加入:

include "/Applications/nginxstack-1.10.1-2/nginx/conf/bitnami/pythonfastcgi.conf";
==========================================================
然後python需安裝flup,用來當做fastcgi的gateway(即符合fastcgi協定的SERVER,這樣才能溝通):
pip3 install flup

然後寫一支 wsgi.py,並啟動(以/tmp/python-fcgi.sock監聽):
==========================================================
#!/usr/local/bin/python3
#coding=utf-8

from html import escape
import sys, os
from flup.server.fcgi import WSGIServer

def app(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    yield '<h1>FastCGI Environment</h1>'
    yield '<table>'
    for k, v in sorted(environ.items()):
        yield '<tr><th>%s</th><td>%s</td></tr>' % (escape(k), escape(v))
    yield '</table>'

if __name__ == '__main__':
    # WSGIServer(app, bindAddress=('127.0.0.1',10240)).run()
    WSGIServer(app, bindAddress='/tmp/python-fcgi.sock').run()
==========================================================
修改為執行檔並執行,再執行nginx:
chmod +x wsgi.py
./wsgi.py
systemctl start nginx

uWSGI是一個軟體專案名稱,而flup本身就是一個架構在uWSGI專案之上的server,同時支援了:
wsgi-->可支援fastcgi
uwsgi-->python web server protocol
http協定
等,因此Nginx也可以改用uwsgi(設定uwsgi_pass)去執行,可參考下面最後一個鏈結

ref:
https://httpd.apache.org/mod_fcgid/mod/mod_fcgid.html
https://httpd.apache.org/docs/2.4/howto/cgi.html
http://uwsgi-docs.readthedocs.io/en/latest/WebServers.html
https://segmentfault.com/a/1190000003993249
https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-14-04

沒有留言:

張貼留言