【Python】CGIで掲示板を作成する

cgiモジュールを用いて、掲示板を作成する。

import cgi
import cgitb
import sys
import io
import sqlite3
import os

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

class Database:
  def __init__(self,_dbname='main.db'):
    self.dbname = _dbname
    if os.path.isfile(self.dbname) != True:
      self.create_bd()
      self.create_table()

  def create_bd(self):
    conn = sqlite3.connect(self.dbname)
    conn.close()

  def create_table(self):
    conn = sqlite3.connect(self.dbname)
    cur = conn.cursor()
    cur.execute('CREATE TABLE users(id INTEGER PRIMARY KEY AUTOINCREMENT, name STRING, message STRING)')
    conn.close()

  def write_data(self,_name,_message):
    conn = sqlite3.connect(self.dbname)
    cur = conn.cursor()
    cur.execute(f'INSERT INTO users(name,message) values("{_name}", "{_message}")')
    conn.commit()
    conn.close()

  def read_data(self):
    conn = sqlite3.connect(self.dbname)
    cur = conn.cursor()
    cur.execute('SELECT * FROM users')
    data = cur.fetchall()
    conn.close()
    return data

form = cgi.FieldStorage()
name = form.getvalue('hn','')
message = form.getvalue('msg','')

db = Database()
redirect = ''
if name != '' and message != '':
  db.write_data(name,message)
  redirect = '<meta http-equiv="refresh" content="0;url=index.py">'
users_table = '<table border=1 width="100%"><th width="10%">ID</th><th width="20%">名前</th><th width="70%">メッセージ</th>'
for x in db.read_data():
  users_table += '<tr><td>'+str(x[0])+'</td><td>'+str(x[1])+'</td><td>'+str(x[2])+'</td></tr>'
users_table += '</table>'

header = 'Content-Type: text/html; charset=utf-8'
body = f'''
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    {redirect}
    <title>【Python】CGIで掲示板を作成する</title>
  </head>
  <body style="background-color:lightyellow">
    <h1>いのはの掲示板へようこそ!</h1>
    <form action="index.py" method="post">
      <p>名前:<input type="text" name="hn"></p>
      <p>メッセージ:<input type="text" name="msg"></p>
      <input type="submit" name="submit">
   </form>
    <hr/>
    {users_table}
  </body>
</html>
'''

print(header)
print()
print(body)

サンプルページ

タイトルとURLをコピーしました