我已经阅读了教程,因为我使用了三个独立的东西: 1.烧瓶作为服务器2. PyMongo作为MongoDB驱动程序3. PyMODM作为模式创建者
我已经糊涂了。
首先,我使用PyMODM定义了模式:
from pymongo import TEXT
from pymongo.operations import IndexModel
from pymodm import connect, fields, MongoModel, EmbeddedMongoModel
class GoalPosition(EmbeddedMongoModel):
x = fields.IntegerField()
y = fields.IntegerField()
class GoalOrientation(EmbeddedMongoModel):
x = fields.IntegerField()
class Goal(EmbeddedMongoModel):
position = fields.EmbeddedDocumentField(GoalPosition)
orientation = fields.EmbeddedDocumentField(GoalOrientation)
class Path(MongoModel):
path = fields.EmbeddedDocumentListField(Goal)从上面,我的想法是建立两种类型的模式:目标和路径。最后,目标看起来是这样的:
{
"position": {
"x": "1",
"y": "6"
},
"orientation": {
"x": "0"
}
}路径将是一系列的目标。有了我的模式,最大的问题是,如何使用它与我的MongoDB数据库进行通信?下面是我的小服务器代码:
from flask import Flask, render_template, flash, redirect, url_for, session, request, logging
from flask_pymongo import PyMongo
from flask import jsonify
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb+srv://user:pass@cluster0-qhfvu.mongodb.net/test?retryWrites=true"
mongo = PyMongo(app)
@app.route('/goal', methods=['GET', 'POST'])
def goals():
if request.method == 'GET':
goals = mongo.db.goals.find()
return jsonify(goals)
elif request.method == 'POST':
position = request.body.position
orientation = request.body.orientation
print position
flash("Goal added")
@app.route('/goal/<id>')
def goal(id):
goal = mongo.db.goals.find_one_or_404({"_id" : id})
return jsonify(goal)因此,通过只关注路由‘/目标值’的GET方法,如何从我的数据库中检索所有目标消息?
此外,我还想知道,如何在'/ Goal /‘?上检索最后一个目标消息
发布于 2018-12-18 20:06:28
def goals():
if request.method == 'GET':
goals = mongo.db.goals.find()
return jsonify(goals)您已经在检索目标集合中的所有记录。下面的示例将为您提供最新的单一记录。
def goals():
if request.method == 'GET':
goals = mongo.db.goals.find().sort({'_id',-1}).limit(1)
return jsonify(goals)。
def goals():
if request.method == 'GET':
goals = mongo.db.goals.find().sort({'_id',-1})
return jsonify(goals)上面的示例将按降序返回目标集合中所有数据的列表,这意味着最后的更新将位于顶部。
找出
mongo.db.goals.find_one({"_id": ObjectId(id)})https://stackoverflow.com/questions/53832070
复制相似问题