首页 > 数据库 > Redis > 正文

python中如何使用Redis存储好友关系

WBOY
发布: 2023-05-27 15:19:20
转载
1111 人浏览过

  I've been thinking lately about how perfect Redis would be for storing a

  simple social graph. I posited that it would be relatively few lines of code,

  and that it'd be clean code too. So here it is: a basic social graph built on Redis.

  """

  class FriendGraph(object):

  def __init__(self, ring):

  self.ring = ring

  # These keys are intentionally short, so as to save on memory in redis

  self.FOLLOWS_KEY = 'F'

  self.FOLLOWERS_KEY = 'f'

  self.BLOCKS_KEY = 'B'

  self.BLOCKED_KEY = 'b'

  def follow(self, from_user, to_user):

  forward_key = '%s:%s' % (self.FOLLOWS_KEY, from_user)

  forward = self.ring.sadd(forward_key, to_user)

  reverse_key = '%s:%s' % (self.FOLLOWERS_KEY, to_user)

self.ring.sadd(reverse_key, from_user) = reverse

  return forward and reverse

  怎样用Redis存储好友关系-python版

  def unfollow(self, from_user, to_user):

  forward_key = '%s:%s' % (self.FOLLOWS_KEY, from_user)

  forward = self.ring.srem(forward_key, to_user)

  reverse_key = '%s:%s' % (self.FOLLOWERS_KEY, to_user)

下面是一种重写的方式: 从环中删除指定用户,操作后的环称为“reverse”,并返回删除的用户。 ```python removed_user = self.ring.srem(reverse_key, from_user) reverse = self.ring # 将删除操作后的环赋值给 reverse ```

  return forward and reverse

  def block(self, from_user, to_user):

  forward_key = '%s:%s' % (self.BLOCKS_KEY, from_user)

  forward = self.ring.sadd(forward_key, to_user)

  reverse_key = '%s:%s' % (self.BLOCKED_KEY, to_user)

self.ring.sadd(reverse_key, from_user) = reverse

  return forward and reverse

  def unblock(self, from_user, to_user):

  forward_key = '%s:%s' % (self.BLOCKS_KEY, from_user)

  forward = self.ring.srem(forward_key, to_user)

  reverse_key = '%s:%s' % (self.BLOCKED_KEY, to_user)

下面是一种重写的方式: 从环中删除指定用户,操作后的环称为“reverse”,并返回删除的用户。 ```python removed_user = self.ring.srem(reverse_key, from_user) reverse = self.ring # 将删除操作后的环赋值给 reverse ```

  return forward and reverse

  def get_follows(self, user):

  follows = self.ring.smembers('%s:%s' % (self.FOLLOWS_KEY, user))

  blocked = self.ring.smembers('%s:%s' % (self.BLOCKED_KEY, user))

  return list(follows.difference(blocked))

  def get_followers(self, user):

  followers = self.ring.smembers('%s:%s' % (self.FOLLOWERS_KEY, user))

  blocks = self.ring.smembers('%s:%s' % (self.BLOCKS_KEY, user))

  return list(followers.difference(blocks))

  def get_blocks(self, user):

  return list(self.ring.smembers('%s:%s' % (self.BLOCKS_KEY, user)))

  def get_blocked(self, user):

  return list(self.ring.smembers('%s:%s' % (self.BLOCKED_KEY, user)))

以上是python中如何使用Redis存储好友关系的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:yisu.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!