フォームから送信された内容をデータベースに書き込む。
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()
if name != '' and message != '':
db.write_data(name,message)
header = 'Content-Type: text/html; charset=utf-8'
body = f'''
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>【Python】フォームから送信された内容をデータベースに書き込む</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/>
<p>{name}</p>
<p>{message}</p>
</body>
</html>
'''
print(header)
print()
print(body)