TL;DR
- PythonからRedisにアクセスするためのライブラリを知りたい
-
redis-py
というものを使うらしいので、ちょっと試してみた
Redis
Key Value Storeの有名どころですね。
値として取れるものも、単純なものだけではなくList、Set、Sorted set、Hash、HyperLogLogs、Streamなどを扱うことができます。
An introduction to Redis data types and abstractions
今回は、Redisの5.0.5
を使用します。Dockerイメージで。
$ docker container run -it --rm --name redis redis:5.0.5
$ docker inspect redis | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "172.17.0.2",
"IPAddress": "172.17.0.2",
PythonからRedisへアクセスするためには、redis-py
というものがメジャーなようなので、こちらを使用して試してみることにします。
環境およびredis-py
のインストール
利用するPythonのバージョン。
$ python3 -V
Python 3.6.7
redis-py
のインストールとバージョン。
$ pip3 install redis
$ pip3 freeze
...
redis==3.2.1
redis-py
を使って、PythonからRedisにアクセスする
とりあえず、Getting Startedを見ながら書いてみましょう。
あんまり使い方が書かれていないのですが、コードを見つつ、なんとなく書いてみます…。
hello-redis.py
import redis
redis_client = redis.Redis(host = '172.17.0.2', port = 6379)
## Simple
redis_client.set('key1', 'value1')
assert redis_client.get('key1') == b'value1'
assert redis_client.get('key1').decode('utf-8') == 'value1'
## Hash
redis_client.hmset('hash_key1', { 'member1': 'hash_value1', 'member2': 'hash_value2' })
assert redis_client.hget('hash_key1', 'member1') == b'hash_value1'
assert redis_client.hgetall('hash_key1') == { b'member1': b'hash_value1', b'member2': b'hash_value2' }
実行。
$ python3 hello-redis.py
動きました。
ところで、レスポンスがbyte
で返ってきているので、ひたすらdecode
することになります。
ここで、ドキュメントをちゃんと見ると、decode_responses
をTrue
にすればよいとあるのでこちらを使ってみましょう。
If all string responses from a client should be decoded, the user can specify decode_responses=True to Redis.init. In this case, any Redis command that returns a string type will be decoded with the encoding specified.
hello-redis-decoded.py
import redis
redis_client = redis.Redis(host = '172.17.0.2', port = 6379, decode_responses = True)
## Simple
redis_client.set('key1', 'value1')
assert redis_client.get('key1') == 'value1'
## Hash
redis_client.hmset('hash_key1', { 'member1': 'hash_value1', 'member2': 'hash_value2' })
assert redis_client.hget('hash_key1', 'member1') == 'hash_value1'
assert redis_client.hgetall('hash_key1') == { 'member1': 'hash_value1', 'member2': 'hash_value2' }
スッキリしましたね。
とりあえず、基本的な使い方はこんな感じでしょうか。
接続時のオプションなどは、ちゃんと見た方が良さそうです。
その他の機能
ドキュメントを見ると、コネクションプールなどの機能もあるようです。
Hiredisとか、面白いですね
RedisチームがCで実装したパーサーで、Hiredisをインストールするとredis-py
のパース処理が早くなるようです。
$ pip3 install hiredis
redis-py
自身が、Hiredisを意識したソースコードになっています。
あと、ドキュメントには記載がなさそうですが、Redis Clusterも使えそうなので、そのうち試してみたいところ。
Redis Sentinelのサポートは書かれているんですけどね。
今回はこれくらいで。