Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.
インストール
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
を開けば問題ないでしょう

image.png

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

haniokasai
男子大学生の暇人です。ブログで活動していましたが。VPSオタク。アンチGCPとAWS。国内外のサーバーをたくさん借りてました。JavaとPythonを主に使います。 アイコンはらてちさんから。
https://haniokasai.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away