LoginSignup
8
9

More than 5 years have passed since last update.

Pythonで遊ぼう 入力フォームのテキストを受け取って保存・表示

Posted at

Pythonにしろ何にしろ、とりあえず何か動くものを作らないと面白くないし続きません。さくらインターネットなど、PythonスクリプトがCGIで動作するレンタルサーバーで簡単な送信フォームを作ってみましょう。

sendtext.cgi

#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import sys, codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
from datetime import datetime
import cgi
import csv

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


print """

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
"""

print """
</head>
<body>
"""

try:
    form = cgi.FieldStorage()
    words = form["word"].value
    words = unicode(words,"utf-8")
    today = datetime.now().strftime("%Y/%m/%d %H:%M:%S")

    f = open("date.txt", "ab")
    writer = csv.writer(f, quoting=csv.QUOTE_ALL)
    writer.writerow([words,today])
    f.close()

    print "<p>"+ words + ": " + today + "</p>"

except (TypeError, KeyError):
    print "<p>"+u"入力項目にエラーがあります"+"</p>"

print """
</body>
</html>
"""

こんなイメージでPythonスクリプトを書きます。CGIで動かすことを前提にしているので拡張子は.cgiとしています。index.htmlから送られたフォームを受け取って、そこに送信した日時をくっつけて.txtにCSV形式で保存する簡単なスクリプトです。

HTMLファイルは、

<form method="POST" action="cgi-bin/index.cgi">
  <textarea name="word"></textarea>
  <p><input type="submit" value="送信"></p>
</form>

こういうイメージでOKでしょう。

8
9
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
8
9