LoginSignup
6
8

More than 5 years have passed since last update.

一行でCGIサーバー(1)python編

Last updated at Posted at 2016-01-12

はい、ッターン!

python -m CGIHTTPServer &

終わり。

☆以下の知識があることを前提とします。
下の方に実行例があります。

  • このコマンドを ッターン! したディレクトリが、サーバールートになる
  • 止めるときは後ろにいってしまったプロセスを探してkillする(ps ax | grep python)、もしくはエラーを起こして暴れる
  • xxx.htmlがあれば http://127.0.0.1:8000/xxx.html になる
  • CGIスクリプトは cgi-bin/○○.py に配置 (フォルダが決まっているのがいやなら、普通にサーバー立ち上げて)
  • スクリプトであるならば、実行権限を付与

chmod 0755 cgi-bin/○○.py

  • スクリプトであるならば、実行するプログラムのパスを指定する必要がある

#!/usr/bin/python
# -*- coding: utf-8 -*-

  • ページとしてブラウザに認識してもらいたければ自分でContent-typeを発する(逆に好きなヘッダを送信できるので)

print "Content-type: text/html\n\n"


  • スクリプトとして動かすならば cgi モジュールは使うことになる
#フォーム、クエリからhonyararaという値を取得する
import cgi
form = cgi.FieldStorage()
honyarara = form["honyarara"].value

  • スクリプトが動くかやってみたいとき

vi cgi-bin/test.py
chmod 0755 cgi-bin/test.py
python -m CGIHTTPServer &
curl http://127.0.0.1:8000/cgi-bin/test.py?q=hello

あ、こんにちわ

test.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

import cgi
form = cgi.FieldStorage()

print "Content-type: text/html\n\n"
print form["q"].value
6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8