これまで作ってきたpygameのプログラムを使ってredisへpublishしてみます。とても簡単です。
前々回の記事でredisに関するプログラムがいくつか出てきました。その点の説明をしたいと思います。
前々回の記事→こちら
まずは、グローバル変数として redisComponent と宣言しておきます。あ、import redis もお忘れなく。pip3 install redis もしましたか?
そして、以下のようにredisのホストとポート番号を指定します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
def init(): global CONST global screen global font global fontLarge global potResetTime global coffeeResetTime global errorCode global redisComponent #screen = pg.display.set_mode((480, 320)) screen = pg.display.set_mode((480, 320), FULLSCREEN) ## 省略 ## redisComponent = redis.StrictRedis(host='localhost', port=6379) |
グローバル変数 redisComponent の設定が終わったので、もうpublish出来ます。
以下のように、publish(チャンネル名, 値) を入れるだけです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
def postLog(resetTime, type): global CONST global screen global errorCode global redisComponent ## 省略 ## try : request = urllib.request.Request(url, data) response = urllib.request.urlopen(request) result = response.read() errorCode = font.render("", False, (0, 0, 0)) print("publish") redisComponent.publish(type, resetTime.strftime("%Y-%m-%d %H:%M:%S")) return True except urllib.error.HTTPError as e: errorCode = font.render("E:"+str(e.code), True, (255, 50, 50)) print(e) return False |
これだけでpublishできます。
動作確認をしてみましょう。ターミナルを開きます。
1 |
$sudo apt-get install redis |
(もしインストールしていなければしましょう。)
1 2 3 |
$sudo systemctl start redis-server $redis-cli >> subscribe POT |
以上を入力した後に、publishが実行されるとターミナルに値が表示されます。