LoginSignup
1
1

More than 3 years have passed since last update.

初心者が10分で実装するコメント機能

Posted at

初めに

実務なんかで使えません。
フレームワークとか高尚なものは使いません。
というか使えません。

めっちゃ簡単にできたので投稿

コメント機能

フォームを作り、その下にコメントを表示するだけ
chrome.PNG
コメントを入力、送信
chrome2.PNG
コメントが表示される
chrome3.PNG

手順

1.適当なディレクトリ(Aとする)にcgi-binディレクトリを作る。
2.その中に以下のプログラムをコピペし、comment.pyと名付ける。

comment.py
#! /usr/bin/env python3

import sqlite3
import csv
import cgi
import sys
import io
from datetime import datetime

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")

db_path = "./comment.db"

con = sqlite3.connect(db_path)

con.row_factory = sqlite3.Row

cur = con.cursor()

htmlText = ""

try:
   cur.execute(
       "create table if not exists commentTable(id integer primary key autoincrement, comment text, date datetime);"
   )
except sqlite3.Error as e:
   print("ERROR:", e.args[0])

form = cgi.FieldStorage()
input_comment = form.getvalue("comment")

try:
    if input_comment is not None:
        date = datetime.now().strftime("%Y/%m/%d %H:%M:%S")
        cur.execute("insert into commentTable(comment, date)values(?, ?);", (input_comment, date))

except sqlite3.Error as e:
    print("ERROR:", e.args[0])

def show_database():
    try:
       cur.execute("select * from commentTable;")
    except sqlite3.Error as e:
       print("ERROR:", e.args[0])
       debug = "except completed"
    return 0

show_database()

rows = cur.fetchall()

if not rows:
   htmlText = "コメントはありません。"
else:
   for row in rows:
       if str(row["id"]):
           htmlText += str(row["date"]) + "<br>" + str(row["comment"])+ "</br>"

con.commit()
con.close()

print("Content-type: text/html; charset=utf-8")

print(
   f'''
    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title>コメント</title>
      </head>
      <body>
        <div id="comment-div" class="">
          <h1>コメント</h1>
          <p>コメントを入力して下さい。</p>
          <form name="comment-form" class="" action="comment.py" method="post">
            <textarea name="comment" rows="8" cols="80"></textarea><br>
            <input type="submit" name="" value="送信">
          </form>
          <p>コメント</p>
          {htmlText}
        </div>
      </body>
    </html>
     '''
)

3.ディレクトリAで次のコマンドを実行する。

$ python -m http.server --cgi

これでローカルサーバが立つ。
やめるときはctrl-c
4.以下のurlにアクセスする。
http://localhost:8000/cgi-bin/comment.py

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