Quantcast
Channel: プログラム の個人的なメモ
Viewing all articles
Browse latest Browse all 860

【Python】Python で、簡単なWebアプリ ~ formデータを受け取る ~

$
0
0

■ はじめに

https://blogs.yahoo.co.jp/dk521123/37735805.html
の続き。
今度は、Python で、formデータを受け渡しを行う

補足:Webフレームワークについて

本来であれば、以下のようなWebフレームワークを使うべき。
 * Flask(フラスク)
  => 以下の関連記事を参照のこと
https://blogs.yahoo.co.jp/dk521123/37736310.html
 * Bottle(ボトル)
 * Django(ジャンゴ)
etc...

■ 前提条件

 * 実行環境を以下の関連記事を参考に構築する
https://blogs.yahoo.co.jp/dk521123/33850352.html

■ サンプル

フォルダ構成
demo-main.html ... 受け渡すHTMLファイル
└ cgi-bin
   └ input.py ... 受け取るPythonスクリプト
注意
 * 「cgi-bin」配下、もしくは「htbin」配下にPythonスクリプトを置くこと
  => ここで、ハマった

demo-main.html

受け渡すHTMLファイル
<!DOCTYPE html>
<html lang="jp">
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<form name="Form" method="POST" action="/cgi-bin/result.py">
 ID: <input type="text" size="30" name="id">
 Name: <input type="text" size="30" name="name">
<input type="submit" value="submit" name="button">
</form>
</body>
</html>

/cgi-bin/result.py

受け取るPythonスクリプト
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import io
import sys
import cgi
import cgitb

cgitb.enable()
sys.stdin  = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer,encoding='utf-8')

form = cgi.FieldStorage()

id = form.getvalue('id')
name = form.getvalue('name')

html_body="""
<!DOCTYPE html>
<html lang="jp">
<head>
<meta charset="utf-8">
<title>Demo Result</title>
</head>
<body>
<div><h1>Result</h1></div>
<div>ID: %s</div>
<div>Name: %s</div>
</body>
</html>"""

print("Content-Type: text/html;charset=utf-8")
print()
print(html_body % (id, name))

■ 実行コマンド

# python -m http.server --cgi 【ポート番号】
python -m http.server --cgi 8000

動作確認

 * 以下のサイトをブラウザでアクセスする
アクセスし、id=1000, name=Mikeと入力し、ボタン押下
[[http://localhost:8000/demo-main.html]]


関連記事

Python で、簡単なWebアプリ ~ Hello World編 ~

https://blogs.yahoo.co.jp/dk521123/37735805.html

Python ~はじめの一歩 ~

https://blogs.yahoo.co.jp/dk521123/33850352.html

Webフレームワーク 「Flask」 ~ Hello World編 ~

https://blogs.yahoo.co.jp/dk521123/37736310.html

Viewing all articles
Browse latest Browse all 860

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>