美文网首页
Redis数据结构 之 Lists

Redis数据结构 之 Lists

作者: 诺之林 | 来源:发表于2018-06-26 14:19 被阅读5次

本文的示例代码参考redis-lists.py

Python

pip install redis

pip list | grep redis

Python环境搭建详细参考pyenv

Redis

vim redis-lists.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import pprint
import redis
import unittest


KEY_RECENT_CONTACT = 'recent_contacts'


def add_update_contact(conn, contact):
    pipeline = conn.pipeline(True)
    pipeline.lrem(KEY_RECENT_CONTACT, contact)
    pipeline.lpush(KEY_RECENT_CONTACT, contact)
    pipeline.ltrim(KEY_RECENT_CONTACT, 0, 99)
    pipeline.execute()


def get_autocomplete_list(conn, prefix):
    candidates = conn.lrange(KEY_RECENT_CONTACT, 0, -1)
    matches = []
    for candidate in candidates:
        if candidate.lower().startswith(prefix.lower()):
            matches.append(candidate)
    return matches


class Tests(unittest.TestCase):
    def setUp(self):
        self.conn = redis.Redis()

    def tearDown(self):
        self.conn.delete(KEY_RECENT_CONTACT)
        del self.conn

    def test_add_recent_contact(self):
        for i in xrange(10):
            add_update_contact(self.conn, 'contact-%i-%i' % (i//3, i))
        all = self.conn.lrange(KEY_RECENT_CONTACT, 0, -1)
        pprint.pprint(all)

        add_update_contact(self.conn, 'contact-1-4')
        all = self.conn.lrange(KEY_RECENT_CONTACT, 0, -1)
        pprint.pprint(all)
        self.assertEquals(all[0], 'contact-1-4')

        filter = [c for c in all if c.startswith('contact-2-')]
        contacts = get_autocomplete_list(self.conn, 'contact-2-')
        pprint.pprint(filter)
        pprint.pprint(contacts)
        self.assertEquals(filter, contacts)


if __name__ == '__main__':
    unittest.main()

运行脚本前需要启动Redis: docker run --name redis-lists -p 6379:6379 -d redis 关于Docker详细参考Docker入门

python redis-lists.py
['contact-3-9',
 'contact-2-8',
 'contact-2-7',
 'contact-2-6',
 'contact-1-5',
 'contact-1-4',
 'contact-1-3',
 'contact-0-2',
 'contact-0-1',
 'contact-0-0']
['contact-1-4',
 'contact-3-9',
 'contact-2-8',
 'contact-2-7',
 'contact-2-6',
 'contact-1-5',
 'contact-1-3',
 'contact-0-2',
 'contact-0-1',
 'contact-0-0']
['contact-2-8', 'contact-2-7', 'contact-2-6']
['contact-2-8', 'contact-2-7', 'contact-2-6']
.
----------------------------------------------------------------------
Ran 1 test in 0.009s

OK

参考

相关文章

网友评论

      本文标题:Redis数据结构 之 Lists

      本文链接:https://www.haomeiwen.com/subject/srexeftx.html