API端点仅从mongoDB返回一条记录

时间:2019-02-11 05:36:12

标签: python mongodb api mean-stack

这是我的终点。我必须删除objectId,因为它不是JSON可序列化的。如何返回mongoDB中的所有记录?

from flask import Flask, jsonify, request
from flask_pymongo import PyMongo
from pymongo import MongoClient
from bson import json_util, ObjectId
import json

app = Flask(__name__)

app.config['MONGO_DBNAME'] = 'dummyDB'
app.config['MONGO_URI'] = 'mongodb://user:pass@ec2-35-153-130-169.compute-1.amazonaws.com:27017/dummyDB?authSource=admin'
client = MongoClient ('mongodb://user:pass@ec2-35-153-130-169.compute-1.amazonaws.com:27017/dummyDB?authSource=admin')
db = client['dummyDB']

mongo = PyMongo(app)
@app.route('/jobdata', methods=['GET'])
def get_all_jobdata():
  jobdata = mongo.db.jobdata

  output2 = []

  for q in jobdata.find():
    output2.append({
    'jobcode' : q['jobcode'],
    'date' : q['date'],
    'mean' : q['mean'],
    'std' : q['std']})

    return jsonify({'result' : output2})

1 个答案:

答案 0 :(得分:0)

我需要将return语句移到for循环之外

for q in jobdata2.find():
    output2.append({
    '_id' : q['_id'],
    'jobcode' : q['jobcode'],
    'date' : q['date'],
    'mean' : q['mean'],
    'std' : q['std']})


  return jsonify({'result' : output2})
  ^

Python中的缩进很痛苦