ローカルでも動くSlackBot管理ツールができるまで 〜 WebUI編 2 〜
前回の続き。
[amazonjs asin="479804315X" locale="JP" title="Pythonプロフェッショナルプログラミング第2版"]
新規登録を実装
sites/sites.pyの冒頭の方に以下のimportを追加する。
[python title="sites.pyの最初の方"]
from bottle import get, post, request, response
from bottle import redirect
[/python]
更にsites/sites.pyにhatebu_create関数を作成
[python title="hatebu_create関数を実装"]
@route('/hatebu_create’, method=’GET’)
def hatebu_create():
# 作成ボタンが押されずに/hatebu_createにアクセスが来たらリダイレクト
if request.query.create is None:
redirect("/hatebu")
# データベースアクセス
path = os.path.dirname(os.path.dirname( os.path.abspath(__file__))) + "/db"
connect = sqlite3.connect(path + "/hatena.db")
cursor = connect.cursor()
sql = """
INSERT INTO hatebu_list (
channel,
word,
bookmark_count,
last_post)
VALUES (
?,
?,
?,
?);
"""
# GETパラメータを変数に代入
channel = request.query.channel
word = request.query.word
bookmark_count = request.query.bookmark_count
last_post = '2000-01-01T00:00:00’
# データベースにデータを挿入
cursor.execute(sql,(channel,word,bookmark_count,last_post))
# 変更を更新する
connect.commit()
# データベースを閉じる
connect.close()
# 元ページにリダイレクト
redirect("/hatebu")
[/python]
pythonでsites.pyを実行してブラウザでhttps://localhost:8080/hatebuにアクセスし、作成ボタンを押すと作成できることがわかる。
更新・削除を実装
更新、削除を実装するため、hatebu_updel関数を作成する。
[python title="hatebu_updel関数を実装"]
@route('/hatebu_updel’, method=’GET’)
def hatebu_updel():
# 更新・削除ボタンが押されずに/hatebu_updelにアクセスが来たらリダイレクト
if request.query.updel is None:
redirect("/hatebu")
# データベースアクセス
path = os.path.dirname(os.path.dirname( os.path.abspath(__file__))) + "/db"
connect = sqlite3.connect(path + "/hatena.db")
cursor = connect.cursor()
if request.query.updel == "更新":
# 更新ボタンが押された場合
sql = """
UPDATE hatebu_list SET
channel = ?,
word = ?,
bookmark_count = ?
WHERE id = ?;
"""
idx = request.query.id
channel = request.query.channel
word = request.query.word
bookmark_count = request.query.bookmark_count
# データベースにデータを挿入
cursor.execute(sql,(channel,word,bookmark_count,idx))
else:
# 削除ボタンが押された場合
sql = """
DELETE FROM hatebu_list WHERE id = ?;
"""
idx = request.query.id
# データベースにデータを挿入
cursor.execute(sql,(idx))
# 変更を更新する
connect.commit()
# データベースを閉じる
connect.close()
# 元ページにリダイレクト
redirect("/hatebu")
[/python]
ブラウザで更新、削除が行えるはず。
次回、BOTを作成するため、ワード、チャンネル、ブックマーク数を登録、更新しておくといいかも。
ローカルでも動くSlackBot管理ツールができるまで 〜 Bot編 〜 に続く。
ディスカッション
コメント一覧
まだ、コメントがありません