Edited at

nginxでPythonをCGIとして実行する


インストール

apt install python3 nginx-full fcgiwrap



nginxの設定

vi /etc/nginx/conf.d/fcgiwrap.conf



中身

server {

listen 80;
listen [::]:80;

server_name cgitest;
set $base /home/あなたのhome/DocumentRoot;
root $base/cgitest;

location ~ \.py$ {
gzip off;
include fastcgi_params;
fastcgi_pass unix:/var/run/fcgiwrap.socket;
fastcgi_index index.py;
fastcgi_param DOCUMENT_ROOT $realpath_root;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
}
}



再読込

service nginx restart

service fcgiwrap restart


スクリプトに実行権限を与えておこう

mkdir ~/htdocs

vi test.py
chmod +x test.py


test.py

#!/usr/bin/python3

print("HTTP/1.0 200 OK")
print("Content-type: text/html\n\n")
print("")
print("Hello world")


domainを通す

vi /etc/hosts


127.0.0.1 cgitest

ブラウザで

http://cgitest/test.py

を開けば問題ないでしょう


query(パラメタ)とPOST

url?foo=bar とかPOSTは以下の通り。


test.py

#!/usr/bin/python3

import urllib.parse

print("HTTP/1.0 200 OK")
print("Content-type: text/html\n\n")
print("")
print("url?var=foo <br>")
getquery = os.environ.get('QUERY_STRING')
print(getquery)
query = urllib.parse.parse_qs(getquery)
print(query)
print("post <br>")
posted = input()
print(posted)
print(urllib.parse.parse_qs(posted))



curlテスト

# curl -X POST -d "eee=uuu" -d "aaa=bbbb"  "http://cgitest/test/removeimage.py?py=aa&chin=5"

url?var=foo <br>
py=aa&chin=5
{'py': ['aa'], 'chin': ['5']}
post <br>
eee=uuu&aaa=bbbb
{'eee': ['uuu'], 'aaa': ['bbbb']}



Ref

http://ekzemplaro.org/data_base/doc/web_server/nginx/

https://stackoverflow.com/questions/16253036/python-on-nginx-using-fcgiwrap-upstream-closed-prematurely-fastcgi-stdout-whil

https://qiita.com/gam0022/items/d16cc83a32c5c2efdefc

https://note.nkmk.me/python-urllib-parse-query-string/

https://www.setouchino.cloud/blogs/33#part-5b2df4e0f04afe49