我有一個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)
但是,它不會更新庫存值。我該如何解決這個問題?
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)
否則,您必須檢查:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句