【问题标题】:Flask Pymongo Objectid link not working烧瓶 Pymongo Objectid 链接不起作用
【发布时间】:2018-10-10 18:57:38
【问题描述】:

我正在尝试从名为 games 的 mongo 数据库集合中访问一个新文档,该集合由 _id 提供。但是例如,如果我访问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
}

【问题讨论】:

  • 在查询集合之前,您需要从字符串 id 中创建一个 ObjectId...games.find_one({'_id': ObjectId(id)})

标签: python mongodb flask pymongo


【解决方案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 函数。

【讨论】:

    【解决方案2】:

    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")
    

    你也应该使用“else”条件。

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 1970-01-01
      • 2020-07-06
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 2020-07-24
      相关资源
      最近更新 更多