■ はじめに
https://blogs.yahoo.co.jp/dk521123/37735805.htmlの続き。 今度は、Python で、formデータを受け渡しを行う
補足:Webフレームワークについて
本来であれば、以下のようなWebフレームワークを使うべき。* Flask(フラスク) => 以下の関連記事を参照のことhttps://blogs.yahoo.co.jp/dk521123/37736310.html
* Bottle(ボトル) * Django(ジャンゴ) etc...
■ サンプル
フォルダ構成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]]
参考文献
https://qiita.com/wan-liner/items/15312af7eca45c67f4fdhttps://symfoware.blog.fc2.com/blog-entry-1977.html