LoginSignup
0
0

More than 5 years have passed since last update.

Python3のビルトイン・ウェブ・サーバー(http.server)とCGIを使った簡易WEBサーバー作成してみた初心者メモ

Last updated at Posted at 2018-05-28

作成したきっかけ

豊富なPythonのライブラリをブラウザから利用してみたいので作成してみた。

pythonメモ

  • コメントは#
  • Python3は、print "Hello" ではなくprint("Hello")
  • Python3は、'%d'とか'%+5.3lf'の記法は非推奨らしい

動作環境

  • windows10
  • Powershell
  • Python3.6.3

フォルダ構成とファイル置き場

PHPのビルトイン・ウェブ・サーバーのPHPファイルは、そのまま実行できますが、Pythonファイルは「cgi-bin」フォルダに入れないと動かないんですね。

cgi-bin
     ├test_cgi01.py
     ├test_cgi02.py
     ├test_cgi03.py
   └test_cgi04.py

ビルトイン・ウェブ・サーバーをCGIを付与して起動させる。

通常実行する場合は

python -m http.server 8000

ですがポートの「8000」の部分を「--cgi」に変更する

python -m http.server --cgi

pythonファイル

その1(日本語が文字化け)

test_cgi01.py
# -*- coding: utf-8 -*-

print ('Content-type: text/html; charset=UTF-8\n')

print('abc123日本語123789xyz')

その2(日本語対応)

test_cgi02.py
# -*- coding: utf-8 -*-
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

print ('Content-type: text/html; charset=UTF-8\n')

print('abc123日本語123789xyz')

その3(HTML文をいれてみる)

test_cgi03.py
# -*- coding: utf-8 -*-
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

print ('Content-type: text/html; charset=UTF-8\n')

print ("""
<!DOCTYPE html>
<html lang='ja'>
<html>
<head>
<meta charset='UTF-8'>
<title>CGIスクリプト</title>
</head>
<body>
あいうえお<br>
</body></html>
""")

その4(HTML内に呼び出し記法を入れてみた)

test_cgi04.py
# -*- coding: utf-8 -*-
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

kakikukeko ="かきくけこ"

import datetime
today = str(datetime.date.today())
print ('Content-type: text/html; charset=UTF-8\n')

print ("""
<!DOCTYPE html>
<html lang='ja'>
<html>
<head>
<meta charset='UTF-8'>
<title>CGIスクリプト</title>
</head>
<body>
{0}<br>
現在の時刻は「{1}」です<br>
</body></html>
""".format(kakikukeko,today)
)

その4の結果

かきくけこ
現在の時刻は「2018-06-03」です
0
0
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
0
0