【问题标题】:using mongoDB collection in one page twice在一页中使用 mongoDB 集合两次
【发布时间】:2018-05-30 07:10:02
【问题描述】:

大家好! 我有: 1) mongo 集合:

[{_id:ObjectId("5b0d5fb624d22e1b4843c06b")
collectionName:"collection0"
collectionCaption:"caption1"}

{_id:ObjectId("5b0d5fb824d22e1b4843d4c1")
collectionName:"collection1"
collectionCaption:"caption1"}

{_id:ObjectId("5b0d5fb924d22e1b4843d74a")
collectionName:"collection2"
collectionCaption:"caption1"}

{_id:ObjectId("5b0d5fb924d22e1b4843d7b0")
collectionName:"collection3"
collectionCaption:"caption1"}]

2) 带有视图的烧瓶应用:

def index():
    a = mongo.db.collectionsNames.find()
    return render_template('index.html', collectionsNames=a)

3) 模板:index.html 女巫扩展 base.html。 base.html:

{% extends "bootstrap/base.html" %} 
{% block content %}
    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
        {% for asd in collectionsNames %}
            <a class="dropdown-item" href="/{{ asd["collectionName"] }}">{{ asd["collectionCaption"] }}</a>
        {% endfor %}

    </div>
    {% block contentBase %} {% endblock %}
{% endblock %}

index.html:

{% extends "base.html" %}
{% block contentBase %}
    {% for zxc in collectionsNames %}
        {{ zxc["collectionName"] }}
    {% endfor %}
{% endblock %}

问题是:为什么基数和索引使用同一个集合变量,索引模板什么也没有显示?

但如果在视图中代码是:

def index():
        a = mongo.db.collectionsNames.find()
        b = mongo.db.collectionsNames.find()
        return render_template('index.html', collectionsNames1=a, collectionsNames2=b)

在模板中我使用不同的变量,索引模板显示数据。

【问题讨论】:

  • 如果在视图中函数代码是:a = [{"collectionName":"collection0", "collectionCaption":"col1"}, {"collectionName": "collection1", "collectionCaption": "col2"}, {"collectionName": "collection2", "collectionCaption": "col3"}, ] return render_template('index.html', collectionsNames=a) 然后索引模板显示数据

标签: python mongodb flask


【解决方案1】:

mongo.db.collectionsNames.find() 返回一个游标:print(mongo.db.collectionsNames.find()) 给出&lt;pymongo.cursor.Cursor object at 0x7fd3854d5710&gt;

为了简单起见(但有点错误),游标是一种特定类型的实例,它逐块从数据库中获取数据,所以如果你想要 db 中的 1 000 000 个第一个项目,你实际上并没有存储 1M 项目在 RAM 中,您迭代 100 x 100 个项目(例如)。光标以神奇的方式处理它。

无论如何,您不能在同一个光标上循环多次,并且您永远不应该将光标投射到像 list(cursor_instance) 这样的列表(因为如果您的查询要求 1M 产品,这样做会将所有这些产品添加到 RAM 中)。


那么,现在,您该如何处理。大多数时候我会说最好在需要时调用该方法,如果需要,调用两次。

但是你在 Jinja 环境中,如果我没看错的话,在 Jinja 模板中调用方法是不可能的。

一种方法是使用属性。

class LazyCollection(object):

    @property
    def collections_names(self):
         return mongo.db.collectionsNames.find()


lazycoll = LazyCollection()
return render_template('index.html', collectionsNames=lazycoll)

然后,在您的模板中:

{% for asd in collectionsNames.collections_names %}
    <p>{{ asd.foo }}</p>
{% endfor %}

【讨论】:

  • 感谢您提供如此广泛的回答。但是,您的带有属性的方法不起作用,索引模板仍然没有显示任何内容。据我了解,唯一的方法是为每个 for 循环使用不同的变量。至于我,这很糟糕,而且不是那么“灵活”......
  • 据我所知,这是 pymongo 库(光标...)的功能,根本不是 python 的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
  • 2019-01-28
  • 2017-06-14
相关资源
最近更新 更多