我的环境包括一个mongodb docker容器和一个简单的烧瓶应用程序。
MongoDB: 3.7.1
Pymongo: pymongo==3.6.0
我尝试了几种不同的方法来构造不同的语法。 我从pymongo得到空的结果:
from flask import Flask, render_template, redirect
from pymongo import MongoClient
app = Flask(__name__)
app.config.update(dict(SECRET_KEY='asdfghjkl'
client = MongoClient('mongodb://foouser:foopwd@localhost:27017')
@app.route('/get_uniq_ips', methods=['GET'])
def get_uniq_ips():
db = client.sshnawks
uniqips = db.actors.distinct('src_ip')
#
# works, returns all values from collection showing src_ip field
# uniqips = db.actors.find({}, {'src_ip': 1})
# empty sets
# uniqips = db.actors.distinct({}, 'src_ip')
# uniqips = db.actors.find({}, {'src_ip': 1}).distinct('src_ip')
ipl = []
for i in uniqips:
ipl.append(i)
return render_template('uniqips.html', ipl=ipl)
@app.route('/', methods=['GET'])
def main():
return render_template('index.html')
if __name__=='__main__':
app.run(debug=True)
以下是模板的相关部分:
<tbody>
{% for i in ipl %}
<tr>
<td>{{ i["src_ip"] }}</td>
</tr>
{% endfor %}
</tbody>
呈现模板时会发生的是标签插入文档但没有值。我已经计算了返回的标签,它与集合中的文档总数相同。
我做错了吗?
我尝试了几个其他黑客来处理从find()返回的数据。但是,我无法看到原始列表与策划列表之间的差异。
例如,我尝试了将这个列表缩减到一个集合的技巧:
ipl = []
for i in uniqips:
if i not in ipl:
ipl.append(i)
return render_template('uniqips.html', ipl=ipl)
ipl list具有与uniqips中包含的值相同的值列表。意思是,如果我删除了&#39; if&#39;在for循环中,我得到了与它在那里时相同的列表。
看看文件是什么样的:
{ "_id" : ObjectId("5a89c268d15f5853babff842"), "src_ip" : "158.248.181.217", "interface" : "re0:", "direction" : "in", "rule_num" : "rule 4/(match)", "src_port" : "36790", "dst_port" : "22", "action" : "block", "dst_ip" : "1.2.3.4", "unix_epoch" : "1517220734.472831" }
{ "_id" : ObjectId("5a89c268d15f5853babff843"), "src_ip" : "223.240.222.100", "interface" : "re0:", "direction" : "in", "rule_num" : "rule 4/(match)", "src_port" : "7496", "dst_port" : "22", "action" : "block", "dst_ip" : "1.2.3.4", "unix_epoch" : "1517222539.564746" }
{ "_id" : ObjectId("5a89c268d15f5853babff844"), "src_ip" : "195.154.47.194", "interface" : "re0:", "direction" : "in", "rule_num" : "rule 4/(match)", "src_port" : "41609", "dst_port" : "22", "action" : "block", "dst_ip" : "1.2.3.4", "unix_epoch" : "1517222903.470985" }
{ "_id" : ObjectId("5a89c268d15f5853babff845"), "src_ip" : "103.79.141.180", "interface" : "re0:", "direction" : "in", "rule_num" : "rule 4/(match)", "src_port" : "53789", "dst_port" : "22", "action" : "block", "dst_ip" : "1.2.3.4", "unix_epoch" : "1517225309.861815" }
我做错了什么?
答案 0 :(得分:1)
你的client
连接在哪里?
您的distinct
来电返回list
,为什么不通过/返回?
def get_uniq_ips():
client = MongoClient()
db = client.sshnawks
uniqips = db.actors.distinct("src_ip")
print(uniqips)
return render_template('uniqips.html', ipl=uniqips)
输出:
['158.248.181.217', '223.240.222.100', '195.154.47.194', '103.79.141.180']
测试并运行mongo 3.6和pymongo 3.6