1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

社内Python勉強会でWEBサーバ側の勉強してみた

Posted at

社内の初心者向け勉強会(3回目)でWEBサーバ側プログラムを紹介したので、ココにも記述。

環境:windows10、python3.7

Pythonでは簡単なWEBサーバのライブラリを提供しています。
コマンドだけでWEBサーバの起動が出来ます。
※WEBサービスの説明は割愛

今回は、開発が容易なCGIを使って実装します。
CGIとは、ブラウザからの要求に対して処理を行う仕組みです。

コマンド発行したpath以下を公開するので公開したい場所で
以下のコマンドを実行してください。

>python -m http.server 8888 --cgi

例えば、
d:\work\py_test
上記pathで実行した場合は
d:\work\py_test\ にhtmlを置き
d:\work\py_test\cgi-bin\ に呼び出されるpythonファイルを置きます。

業務システムの場合、サーバ側へのデータ保管はデータベース(以下DB)を使用しますが、
今回、DBを準備するのは時間がかかる為、ファイルにデータを保管する方法で実装してみました。

Pythonでは、ファイル操作もDB操作も簡単に実装出来ます。
操作は似たようなもので
開く → 使う → 閉じる
の手順です。

以下のソースファイルを作成します。

↓ d:\work\py_test\ に置く

file_tesl.html
<html>
	<head><meta http-equiv="content-type" charset="utf-8"></head>
	<body>
	ファイル操作のテスト
	<br>
	<form action="http://localhost:8888/cgi-bin/cgi_file_test.py" method="get">
	    <div>名前を入力<input name="name" id="name" value=""></div>
	    <button>実行</button>
	</form>
	</body>
</html>

↓ d:\work\py_test\cgi-bin\ に置く

cgi_file_test.py
import cgi
import os

# パラメータの受け取り
form = cgi.FieldStorage()
str_name = form["name"].value

# ファイルに書き出し(追記モード)
f = open('./data/test.txt','a')
f.write(str_name + "\n")
f.close()

# ファイルから読込
read_str = ""
with open('./data/test.txt','r') as f:
    for row in f:
       read_str = read_str +"<br>"+ row.strip()

# htmlで出力する
print ("Content-Type: text/html")
print ()
print ("<html><body>")
print ("これまでに入力された名前は",read_str,"<br>")
print ("<a href=\"../file_test.html\">戻る</a>")
print ("</body></html>")

WEBブラウザに以下のURLを入力して表示して動作を確認します。

http://locahost:8888/file_tesl.html

WEBブラウザで表示したら、名前入力して「実行」押下してみよう。
画面遷移したら、「戻る」押下し、
名前をドンドン入力してみよう。

追記されていくのが確認できます。

この様にPythonではcgiが簡単に作れるだけでなくファイル操作も超簡単に出来てしまいます。

実業務のWEBシステムではフレームワークを使うので、この様なcgiを書くことはホボ無いですが簡単にWEBシステムを実現できるので色々試してみてはいかがでしょうか。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?