Flask Pymongo Objectid 链接不起作用



我正试图从_id名为games的mongo数据库集合中访问一个新文档。但是例如,如果我访问localhost:5000/solutie/5ae71f3e8e442b090e4c313b它会给我错误:ValueError: View function did not return a response所以它不会通过if,我认为我应该将_id的值转换为另一种类型,但我不知道如何。

这是我的烧瓶代码:

@app.route('/solutie/<id>')
def solu(id):
    games = mongo.db.games
    game_user = games.find_one({'_id' : id})
    if game_user:
        return id

这是我名为 games 的 mongo 数据库集合:

{
    "_id": {
        "$oid": "5ae71f3e8e442b090e4c313b"
    },
    "sursa1": "nothingfornow",
    "sursa2": "nothing4now",
    "corectat": 0,
    "player2": "test",
    "player1": "test2",
    "trimis1": 1,
    "trimis2": 1
}

有一个对象类型转换器可用于 URL 路由:

@app.route('/solutie/<ObjectID:game_id>')
def solu(game_id):
    games = mongo.db.games
    game_user = games.find_one_or_404({'_id' : game_id})
    return game_user

看: https://flask-pymongo.readthedocs.io/en/latest/#flask_pymongo.BSONObjectIdConverter

另外,不要覆盖id(),因为这是一个内置的 Python 函数。

find(( 方法的第二个参数是一个对象,用于描述要包含在结果中的字段。 此参数是可选的,如果省略,则所有字段都包含在结果中。

# @app.route('/solutie/<int:id>') # or
@app.route('/solutie/<string:id>')
def solu(id):
   myclient = pymongo.MongoClient("mongodb://localhost:27017/")
   mydb = myclient["mydatabase"]
   games = mydb["games"]
   game_user = games.find({},{ "_id": id})
   if game_user is not None:
       return id
   else:
     return render_template("index.html")

此外,您应该使用"其他"条件。

最新更新