python - 如何在网页中显示 Redis 排序集元素

标签 python django redis

我正在开发一个项目,该项目使用 Redis 作为数据库模拟一个简单的类似 Twitter 的社交媒体,它包括用于处理 Redis 的 Python 和 Django 框架。 我有一个函数,假设返回一个人时间轴的最后 30 篇帖子,如下所示:

def get_status_messages(conn, uid, timeline='home:', page=1, count=30):
    statuses = conn.zrevrange('%s%s'%(timeline, uid), (page-1)*count, page*count-1)
    pipeline = conn.pipeline(True)
    for id in statuses:
        pipeline.hgetall('status:%s'%id)
    return filter(None, pipeline.execute())

时间线帖子列表存储在一个排序集中,该集合保存帖子 ID 和帖子时间戳,并按后者对列表进行排序。并且每个状态帖子都保存为具有唯一 ID 的哈希。 timeline zset 的名称为“profile:xxx”,其中 xxx 是作者的 ID,每个帖子的名称为“status:yyy”,其中 yyy 是帖子的唯一 ID。 我试图在 html 页面中显示这些帖子,这里是我的主页“ View ”,代表时间轴:

def home(request):
    id = request.session.get('member_id')
    prof=get_status_messages(conn, id, timeline='home:', page=1, count=30)
    fp = open('template/home.html')
    t = Template(fp.read())
    fp.close()
    html = t.render(Context({'item_list': prof.iteritems()}))
    return HttpResponse(html)

最后在时间轴的 html 文件中,我们有这个:

<html>
<head>
    <title>homePage</title>
</head>
<body>
<ol>
{% for key, value in item_list %}
    <li>{{ key }} : {{ value }} </li>
{% endfor %}
</ol>

</body>
</head>
</html>

但是,当我进入时间线页面时,显示了这个错误:

'list' object has no attribute 'iteritems'

我使用了完全相同的模式来读取散列中的项目,而且效果很好。由于我是 python 和 django 的新手,我不太确定可能是什么问题以及为什么它对 zset 不起作用。有谁知道这里可能是什么问题?

编辑:我尝试打印“prof”变量的值,这就是结果。请注意“ Hello World ”,“我是 pegah kiaei!”和 'rrr' 是来自以下用户的测试推文:

[{'uid': '2', 'login': 'p_kiaei', 'id': '7', 'message': '\trrr', 'posted': '1492107986.573'},
 {'uid': '2', 'login': 'p_kiaei', 'id': '6', 'message': '\tI am pegah kiaei!', 'posted': '1492107752.173'},
 {'uid': '2', 'login': 'p_kiaei', 'id': '5', 'message': 'hello world\t', 'posted': '1492107393.602'}] .

提前致谢!

最佳答案

管道中的每个结果都是一个字典。但是管道本身返回一个列表;只需将 prof 直接传递给上下文即可。

编辑 因此,您还需要在模板中添加一个额外的循环:

<ol>
{% for item in item_list %}
  {% for key, value in item %}
      <li>{{ key }} : {{ value }} </li>
  {% endfor %}
{% endfor %}
</ol>

关于python - 如何在网页中显示 Redis 排序集元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43399108/

相关文章:

python - 将 pandoc 和 pandoc-citeproc 与 Jupyter Notebook 结合使用

python - Web2py - 尝试从没有 'for' 句子的 rows 对象获取值

ruby - 创建Redis集群时出现Err : Node 127. 0.0.1:6379未配置为集群节点

python - 子类化 django choicefield 不起作用

python - 从不运行 Django 的站点使用 mod_wsgi 服务 Django 应用程序/

redis - 关于带有 TTL 的键的 redis EVAL 原子性怎么样?

php - Redis "unknown command"错误

python - 如何使用字典更新 Django 模型中的字段?

python - Django读取JSON文件

python - 让 Django/NGINX/uWSGI 在 Ubuntu 14.04 上工作