ローカルでも動くSlackBot管理ツールができるまで 〜 WebUI編 2 〜
前回の続き。
新規登録を実装
sites/sites.pyの冒頭の方に以下のimportを追加する。
from bottle import get, post, request, response from bottle import redirect
更にsites/sites.pyに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でsites.pyを実行してブラウザでhttp://localhost:8080/hatebuにアクセスし、作成ボタンを押すと作成できることがわかる。
更新・削除を実装
更新、削除を実装するため、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")
ブラウザで更新、削除が行えるはず。
次回、BOTを作成するため、ワード、チャンネル、ブックマーク数を登録、更新しておくといいかも。
ローカルでも動くSlackBot管理ツールができるまで 〜 Bot編 〜 に続く。