Skip to content

Instantly share code, notes, and snippets.

@iphysresearch
Last active January 10, 2019 08:18
Show Gist options
  • Save iphysresearch/72c62c03620a4eeb2710a39c8b9d234a to your computer and use it in GitHub Desktop.
Save iphysresearch/72c62c03620a4eeb2710a39c8b9d234a to your computer and use it in GitHub Desktop.
[Redis-py 3.0 demo] a demo for Redis-py 3.0 (http://gree2.github.io/python/2016/05/14/python-with-docker-redis) #redis #demo #python
#! usr/bin/python
#coding=utf-8
# http://gree2.github.io/python/2016/05/14/python-with-docker-redis
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys, os, time
from datetime import datetime, timedelta
import redis # https://github.com/andymccurdy/redis-py
print(redis.__version__)
def redis_info():
"""redis_info"""
info = conn.info()
for key in info:
print("%s: %s" % (key, info[key]))
print('dbsize: %s' % conn.dbsize())
print("ping %s" % conn.ping())
def date_format(date):
"""date_format"""
return date.strftime("%Y%m%d")
def zset_poc():
"""zset_poc"""
# now = datetime.now() - timedelta(days=DAYS)
now = datetime.strptime('20160514112233', '%Y%m%d%H%M%S') - timedelta(days=DAYS)
days = [now - timedelta(days=-day) for day in range(DAYS)]
times = [time.mktime(day.timetuple()) for day in days]
datas = [(date_format(key), value) for key, value in zip(days, times)]
zset_key = 'day_ts'
# remove old test if any
cnt = conn.zcard(zset_key)
if cnt > 0:
print('remove', cnt, 'in zset')
conn.zremrangebyrank(zset_key, 0, cnt)
# field 5 to 9 or -5 to -1
(key_start, ts_start) = datas[-5]
(key_stop, ts_stop) = datas[-1]
# 0 20160504 1462370790.0
# 1 20160505 1462457190.0
# 2 20160506 1462543590.0
# 3 20160507 1462629990.0
# 4 20160508 1462716390.0
# 5 20160509 1462802790.0 <=
# 6 20160510 1462889190.0
# 7 20160511 1462975590.0
# 8 20160512 1463061990.0
# 9 20160513 1463148390.0 <=
for i, (key, value) in enumerate(datas):
print(i, key, value, end='')
if key == key_start:
print('<=', end='')
if key == key_stop:
print('<=', end='')
print()
conn.zadd(zset_key, {key: value}) # I have modified it from redis-py 2.X to 3.0
# ('20160513', 1463148092.0) ('20160509', 1462802492.0)
print(datas[-5], datas[-1])
# ['20160509', '20160510', '20160511', '20160512', '20160513']
print(conn.zrange(zset_key, 5, 9))
print(conn.zrange(zset_key, -5, -1))
print(conn.zrangebyscore(zset_key, ts_start, ts_stop))
if __name__ == '__main__':
# create a redis container with docker
os.system('sudo docker run -p 6379:6379 --name gredis -d redis')
conn = redis.Redis(host='localhost', port=6379, db=1)
try:
DAYS = 10
# redis_info()
zset_poc()
# except Exception as e:
# print(e)
finally:
# cleanup docker container
os.system('sudo docker stop gredis')
os.system('sudo docker rm gredis')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment