示例:给文章储存程序加上文章长度计数功能和文章预览功能

在前面的内容中,我们使用 MSETMGET 等命令构建了一个储存文章信息的程序,在学习了 STRLEN 命令和 GETRANGE 命令之后,我们可以给这个文章储存程序加上两个新功能,其中一个是文章长度计数功能,而另一个则是文章预览功能:

  • 文章长度计数功能用于显示文章内容的长度,读者可以通过这个长度值来了解一篇文章大概有多长,从而决定是否阅读一篇文章。

  • 文章预览功能则用于显示文章开头的一部分内容,这些内容可以帮助读者快速地了解文章本身,并吸引读者进一步阅读整篇文章。

代码清单 2-4 展示了这两个功能的具体实现代码,其中文章长度计数功能是通过对文章内容执行 STRLEN 命令来实现的,而文章预览功能则是通过对文章内容执行 GETRANGE 命令来实现的。


代码清单 2-4 带有长度计数功能和预览功能的文章储存程序:/string/article.py

  1. from time import time # time() 函数用于获取当前 Unix 时间戳
  2.  
  3. class Article:
  4.  
  5. # 省略之前展示过的 __init__()、create() 、update() 等方法……
  6.  
  7. def get_content_len(self):
  8. """
  9. 返回文章内容的字节长度。
  10. """
  11. return self.client.strlen(self.content_key)
  12.  
  13. def get_content_preview(self, preview_len):
  14. """
  15. 返回指定长度的文章预览内容。
  16. """
  17. start_index = 0
  18. end_index = preview_len-1
  19. return self.client.getrange(self.content_key, start_index, end_index)

get_content_len() 方法的实现非常简单直接,没有什么需要说明的。与此相比,get_content_preview() 方法显得更复杂一些,让我们来对它进行一些分析。

首先,get_content_preview() 方法会接受一个 preview_len 参数,用于记录调用者指定的预览长度。接着程序会根据这个预览长度,计算出预览内容的起始索引和结束索引:

  1. start_index = 0
  2. end_index = preview_len-1

因为预览功能要做的就是返回文章内容的前 preview_len 个字节,所以上面的这两条赋值语句要做的就是计算并记录文章前 preview_len 个字节所在的索引范围,其中 start_index 的值总是 0 ,而 end_index 的值则为 preview_len 减一。举个例子,假如用户输入的预览长度为 150 ,那么 start_index 将被赋值为 0 ,而 end_index 将被赋值为 149

最后,程序会调用 GETRANGE 命令,根据上面计算出的两个索引,从储存着文章内容的字符串键里面取出指定的预览内容:

  1. self.client.getrange(self.content_key, start_index, end_index)

以下代码展示了如何使用文章长度计数功能以及文章预览功能:

  1. >>> from redis import Redis
  2. >>> from article import Article
  3. >>> client = Redis(decode_responses=True)
  4. >>> article = Article(client, 12345)
  5. >>> title = "Improving map data on GitHub"
  6. >>> content = "You've been able to view and diff geospatial data on GitHub for a while, but now, in addition to being able to collaborate on the GeoJSON files you upload to GitHub, you can now more easily contribute to the underlying, shared basemap, that provides your data with context."
  7. >>> author = "benbalter"
  8. >>> article.create(title, content, author) # 将一篇比较长的文章储存起来
  9. True
  10. >>> article.get_content_len() # 文章总长 273 字节
  11. 273
  12. >>> article.get_content_preview(100) # 获取文章前 100 字节的内容
  13. "You've been able to view and diff geospatial data on GitHub for a while, but now, in addition to bei"