【问题标题】:how to update mongodb using button in html, pymongo如何使用 html、pymongo 中的按钮更新 mongodb
【发布时间】:2022-01-10 06:13:46
【问题描述】:

我有一个base.html,其中包含项目和供用户单击的按钮。

                                <p class="card-text">{{data[0].name}}</p>
                                <div class="d-flex justify-content-between align-items-center">
                                <div class="btn-group">
                                    <form action="/update/<%= data[0]._id %>" method="PATCH">
                                    <p style="margin-right:5px;">Available: {{data[0].inventory}}</p>
                                    <button type="button" class="btn btn-sm btn-outline-secondary">Add to cart</button>
                                    </form>
                                </div>

我有运行服务器的hello.py python 文件。

from flask import Flask, render_template, redirect, request, url_for
from pymongo import MongoClient
from bson.objectid import ObjectId
app = Flask(__name__)
 

@app.route('/',methods=['GET'])
def mongoTest():
    client = MongoClient('mongodb://localhost:27017/')
    db = client.ecommerce
    collection = db.items
    results = collection.find()
    # client.close()
    return render_template('base.html', data=results)


@app.route("/update/:id", methods=["PATCH"])
def update_inventory(id):    
    client = MongoClient('mongodb://localhost:27017/')
    db = client.ecommerce
    id=request.values.get("_id")    
    db.items.update_one({ '_id': id}, {'$inc': {'inventory': -1}}, upsert=False)
    results2 = db.items.find()
    return render_template('base.html', data=results2)

if __name__ == '__main__':
    app.run(debug=True)

但是,它不会更新库存值。 我该如何解决这个问题?

【问题讨论】:

    标签: python mongodb flask nosql pymongo


    【解决方案1】:

    id 是字符串吗?如果是这样,则需要将其转换为 ObjectId。 (在大多数情况下,您让 mongo 处理 id,因此 id 是 ObjectId,而不是字符串)。

    from bson.objectid import ObjectId
    
    @app.route("/update/:id", methods=["PATCH"])
    def update_inventory(id):    
        client = MongoClient('mongodb://localhost:27017/')
        db = client.ecommerce
        id = ObjectId(request.values.get("_id"))
        db.items.update_one({ '_id': id}, {'$inc': {'inventory': -1}}, upsert=False)
        results2 = db.items.find()
        return render_template('base.html', data=results2)
    

    否则,您必须检查:

    • 如果id存在,如果不存在则返回错误?
    • “items”集合不存在? (不是项目也不是项目?)

    【讨论】:

    • 哦,ID 是 ObjectId!那我该如何处理..?并且“项目”集合存在
    • 只看答案:你必须将字符串传递给ObjectId:
    • 这个 html 部分是否正确?获取 id?
    • 并拥有@app.route("/update/:id", methods=["PATCH"])
    • :id其实是在获取id
    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 2021-11-30
    • 2015-08-27
    • 1970-01-01
    • 2012-11-22
    • 2020-07-04
    • 2018-08-15
    • 2011-03-09
    相关资源
    最近更新 更多