使用Flask和Python从Mongo中提取多个记录
我还在这里学习,目前正在尝试使用FLASK来创建一个Restful接口。
我想做的是从一个mongo数据库中提取一组记录。我已经成功使用了find_one(),现在在探索如何遍历一个游标。
这段代码只显示了一条记录,而我知道至少有5条。
@app.route('/oer/api/v1.0/getType/', methods = ['GET'])
def getType():
# Prepare a dictionary object to hold the result of any processing
result = {}
# Get hold of DB connection
db_connection = getDbConnection()
db = db_connection['OER']
# Extract all records passed for the paramater that matches "Type": ie MOOC
oerType = request.args.get("oerType");
# test to see that there is something in the string if so try to get a record
# Not doing this test yet lets get it working with a known record first
for d in db.oer_records.find({"Type":oerType}):
result.update(make_public_page(d))
return jsonify(result)
所以它能工作,但只返回了一条json文档,而不是一组记录?我以为result.update会在每次循环时添加一条新记录。顺便说一下,make_public_page()会去掉BISON ID,以便jsonify能够正常工作。
这是它返回的内容:
{
"Account No": 1,
"Country/ continent": "Argentina",
"Educational Level": "Schools",
"Educational Level (ISCED)": "2|3",
"End year": "",
"Funders": "",
"Geolocation": "",
"Initiative HQ address": "",
"Initiative HQ city": "",
"Initiative URL": "http://www.gleducar.org.ar",
"Type": "OER"
}
任何帮助都非常感谢。
谢谢
1 个回答
2
当你使用 dict.update(dict2)
时,你是在把字典 dict2 的键值对添加到 dict 中,这样就变成了一个大的字典。如果你想要的其实是创建一个字典的列表,那就需要用不同的方法。
mylist = []
mylist.append(dict)
这段话可以用你的代码来表示:
@app.route('/oer/api/v1.0/getType/', methods = ['GET'])
def getType():
# Prepare a dictionary object to hold the result of any processing
result = [] # create a list instead of dict
# Get hold of DB connection
db_connection = getDbConnection()
db = db_connection['OER']
# Extract all records passed for the paramater that matches "Type": ie MOOC
oerType = request.args.get("oerType");
# test to see that there is something in the string if so try to get a record
# Not doing this test yet lets get it working with a known record first
for d in db.oer_records.find({"Type":oerType}):
result.append(make_public_page(d)) # append to the list of dicts
return jsonify(items=result)