Ooredis

1,560 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,560
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Ooredis

  1. 1. OOREDIS
  2. 2. OOREDIS是什么:一个Redis的Python库,基于redis-py。目标: 1. 以Key对象为单位操作Redis的数据结构 2. 提供一组Pythonic的API 3. 提供方便的类型转换机制
  3. 3. OOREDIS是什么:一个Redis的Python库,基于redis-py。目标: 1. 以Key对象为单位操作Redis的数据结构 2. 提供一组Pythonic的API 3. 提供方便的类型转换机制
  4. 4. REDIS以函数为单位:Keys: DEL, KEYS, TTL...Strings: SET, GET, GETSET...Hashs: HSET, HDEL, HGET...Lists: LPUSH, RPUSH, LPOP, RPOP...Set: SADD, SREM, SPOP...Sorted Sets: ZADD, ZREM......
  5. 5. REDIS-PY以客户端对象为单位: >>> from redis import Redis >>> r = Redis() >>> r.lpush(numbers, one) 1L >>> dir(r) >>> [..., append, bgrewriteaof, bgsave, blpop,brpop, brpoplpush, config_get, config_set,connection_pool, dbsize, decr, ...]
  6. 6. OOREDIS以Key对象为单位: 根据其作用,Redis的函数在OOREDIS中被归为一个个Python类。
  7. 7. REDIS函数->OOREDIS类redis: Key(ttl, expire, del, ...) / / | Hash List SortedSet Set String | | | | | HGET LPUSH ZADD SADD SET HSET RPUSH ZRANK SUNION GET HLEN LRANGE ZREM SPOP SETNX ... ... ... ... ... | | | | |ooreids: Dict List SortedSet Set SingleValue, Counter
  8. 8. OOREDIS以Key对象为单位: 根据其作用,Redis的函数在OOREDIS中被归为一个个python类。 每个OOREDIS类以一个Key(或者说,key name,键名)作为构造函数参数,生成相应的Key对象。
  9. 9. OOREDIS例子: >>> greet = SingleValue(greeting) >>> greet.set(hello world) >>> greet.get() uhello world
  10. 10. OOREDIS例子2: >>> project = Dict(ooredis-project) >>> project[name] = ooredis >>> project[language] = Python >>> project[author] = huangz
  11. 11. OOREDIS是什么:一个Redis的Python库,基于redis-py。目标: 1. 以Key对象为单位操作Redis的数据结构 2. 提供一组Pythonic的API 3. 提供方便的类型转换机制
  12. 12. Key所有Key对象的基类,子类通过继承它以获得以下通用命令: __init__(self, name, client=None, type_case=None) name, delete, exists, expire, expireat, persist, ttl, sort
  13. 13. Key例子: >>> books = List(my_book_list) >>> dir(books) [__abstractmethods__, ..., exists, expire, expireat,index, lpop, lpush, name, persist, ..., ttl] >>> >>> from ooredis.mix.key import Key >>> issubclass(List, Key) True
  14. 14. SingleValue储存单个值的对象: set(value, preserve=False, expire=None) get() getset(value)
  15. 15. SingleValue例子:  >>> phone = SingleValue(china_mobile) >>> phone.set(10086) >>> phone.get() 10086 >>> phone.getset(123123) 10086 >>> phone.get() 123123
  16. 16. Counter计数器对象,继承自SingleValue: incr(increment=1) += decr(decrement=1) -= set, get, getset
  17. 17. Counter例子: >>> counter = Counter(hit_count) >>> counter.incr() 1 >>> counter.incr(5) 6 >>> counter += 10086 >>> counter.get() 10092 >>> counter.decr() 10091
  18. 18. Dict字典对象,提供O(1)复杂度的读/写操作: __setitem__, __getitem__, __delitem__, __iter__, __contains__, __len__ incr(), decr() setdefault(), get() items(), keys(), values() iteritems(), iterkeys(), itervalues(), pop(), popitems(), clear(), update()
  19. 19. Dict例子: >>> project = Dict(ooredis-project) >>> project[name] = ooredis >>> project[version] = 1.0 >>> project[language] = Python >>> >>> project.items() [(name, uooredis), (version, 1.0),(language, uPython)] >>> author in project False
  20. 20. List列表对象,提供slice,以及双向的push/pop等操作: __contains__, __getitem__, __delitem__, __setitem__, __iter__, __len__ lpush, lpop, blpop, rpush, rpop, brpop, rpoplpush, brpoplpush remove, count, index
  21. 21. List例子: >>> books = List(my_book_list) >>> books.rpush(on lisp) >>> books.rpush(pro python) >>> books.lpush(design patterns) >>> >>> [book.title() for book in books] [uDesign Patterns, uOn Lisp, uPro Python] >>> books.lpop() udesign patterns
  22. 22. Set集合对象,支持Key对象之间或Key对象和Python集合之间的对象运算: isdisjoint, __le__, __lt__, __ge__, __gt__ __or__, __ror__, __and__, __rand__, __sub__, __rsub__, __xor__, __rxor__ __len__, __iter__, __contains__ add, remove, pop, random, move
  23. 23. Set例子: >>> jack = Set(jack_following) >>> jack.add(tom); jack.add(peter) >>> >>> # Set object & Set object >>> jack & jack set([upeter, utom]) >>> >>> # Set object | Python set >>> jack | {tom, marry} set([marry, upeter, utom])
  24. 24. SortedSet有序集合,常用于排名或频率统计: __len__, __contains__, __setitem__, __getitem__, __delitem__, remove, rank, score, incr, decr
  25. 25. SortedSet例子: >>> fruit = SortedSet(fruit_price) >>> fruit[apple] = 8.3 >>> fruit[banana] = 7.5 >>> fruit[orange] = 5 >>> >>> fruit[0] {score: 5.0, value: uorange} >>> list(reversed(fruit))[:2] [{score: 8.3, value: uapple}, {score: 7.5, value:ubanana}]
  26. 26. OOREDIS是什么:一个Redis的python库,基于redis-py。目标: 1. 以Key对象为单位操作Redis的数据结构 2. 提供一组Pythonic的API 3. 提供方便的类型转换机制
  27. 27. REDISRedis的数据都是以字符串格式保存的: redis> SET PI 3.1415926 OK redis> GET PI "3.1415926"
  28. 28. REDIS-PY每次都手动转型太不低碳了: >>> from redis import Redis >>> r = Redis() >>> r.set(PI, 3.1415926) True >>> r.get(PI) 3.1415926 >>> float(r.get(PI)) 3.1415926
  29. 29. OOREDIS在ooreids中,你可以通过给Key对象传入TypeCase类来控制值的转型:>>> from ooredis.type_case import FloatTypeCase>>>>>> f = Dict(floats, type_case=FloatTypeCase)
  30. 30. 自带的TypeCase类ooredis自带了一些常用的TypeCase类: GenericTypeCase # 接受int(long), float,  # string, unicode IntTypeCase # int(long) FloatTypeCase # float StringTypeCase # sting, unicode都转化成unicode JsonTypeCase # Json SerializeTypeCase # Pickle
  31. 31. GenericTypeCaseGenericTypeCase是Key对象的默认type_case值:>>> from ooredis import *>>> jack = Dict(jack_profile)>>> jack[name] = Jack Loz>>> jack[age] = 35>>> jackDict Key jack_profile: {age: 35, name: uJack Loz}
  32. 32. IntTypeCase>>> from ooredis.type_case import IntTypeCase>>>>>> nums = Set(nums, type_case=IntTypeCase)>>> nums.add(10086)>>> nums.add(2011)>>> numsSet Key nums: set([2011, 10086])>>>>>> nums.add(hello)ValueError: invalid literal for int() with base 10: hello
  33. 33. FloatTypeCase>>> from ooredis.type_case import FloatTypeCase>>>>>> const = Dict(const, type_case=FloatTypeCase)>>>>>> const[pi] = 3.1415926>>> const[e] = 2.71828>>> constDict Key const: {pi: 3.1415926, e: 2.71828}
  34. 34. StringTypeCase>>> from ooredis.type_case import StringTypeCase>>> friends = Set(my_friend, type_case=StringTypeCase)>>> friends.add(jack)>>> friends.add(marry)>>> friends.add(unicode(harry))>>> friendsSet Key my_friend: set([umarry, ujack, uharry])
  35. 35. JsonTypeCase>>> from ooredis.type_case import JsonTypeCase>>> site = SingleValue(site, type_case=JsonTypeCase)>>> google = {name: google, type: search engine, url: www.google.com}>>> site.set(google)>>> site.get(){uurl: uwww.google.com, utype: usearch engine,uname: ugoogle}
  36. 36. SerializeTypeCase>>> from ooredis.type_case import SerializeTypeCase>>> obj = SingleValue(book, type_case=SerializeTypeCase)>>> class Book:... name = Learning Android,...>>> obj.set(Book())>>> book = obj.get()>>> book.nameLearning Android
  37. 37. 编写你自己的TypeCase类TypeCase类的两个静态方法:to_redis和to_pythonclass NewTypeCase: @staticmethod def to_redis(value): pass # 将值/对象转为Redis能保存的值(字符串,整数,浮点) @staticmethod def to_python(value): pass # 将从Redis取出的字符串值转换回原来的值/对象
  38. 38. FloatTypeCase示例class FloatTypeCase: """ 将python值转换为float类型。 """ @staticmethod def to_redis(value): return float(value) @staticmethod def to_python(value): if value == None: # 某些方法会返回None            return None        return float(value)
  39. 39. OOREDIS 需求, 使用, 文档...
  40. 40. 需求Python: 2.7Redis: 2.2redis-py: 2.4.9
  41. 41. 下载OOREDIS$ cd /tmp/$ git clone git://github.com/huangz1990/ooredis.gitCloning into ooredis......Resolving deltas: 100% (34/34), done.$ cd ooredis/$ sudo mv ooredis/ /usr/lib/python2.7/site-packages/$ python2Python 2.7.2 (default, Jun 29 2011, 11:17:09)[GCC 4.6.1] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> from ooredis import *
  42. 42. 使用OOREDIS>>> from ooredis import *>>> dir()[Counter, Dict, List, Set, SingleValue, SortedSet,__builtins__, __doc__, __name__, __package__,connect, get_client, type_case]>>>>>> connect(db=5) # 指定数据库<redis.client.Redis object at 0xb73db1cc>>>> ...
  43. 43. 文档?!目前还没有,遇上问题请dir和help.>>> dir(Set)[__and__, __class__, ..., random, remove, ttl]>>>>>> help(Set.add)add(self, element): 将element加入到集合当中。       如果element已经是集合的成员,不做动作。 ...
  44. 44. 项目地址 https://github.com/huangz1990/ooredis 联系方式twitter: @huangz1990gmail: huangz1990豆瓣: http://www.douban.com/people/i_m_huangz/
  45. 45. EOF

×