【问题标题】:Shopping cart, how can I caclulate the total price of all the items in my cart购物车,如何计算我购物车中所有商品的总价
【发布时间】:2019-12-09 07:43:50
【问题描述】:

我已经成功地使用烧瓶会话添加到购物篮,但我在计算所有产品的总价格时遇到了麻烦。我试图设置一个变量,该变量使用列表中的值计算价格,但这不起作用,而是返回第一个项目。有人能指出我正确的方向吗?

@app.route("/Menu")
def menu():
    MenuItems = Menu.query.all()
    return render_template("menu.html", MenuItems=MenuItems)

@app.route("/AddToCart", methods=["POST", "GET"])
def addToCart():
    itemId = int(request.form.get("productId"))
    MenuItem = Menu.query.get(itemId)

    if MenuItem is None:
        return render_template("error.html", errorMessage="There has been an issue adding this item to your basket")

    sVars = session['cart']

    sVars.append([str(MenuItem.ItemName), float(MenuItem.ItemPrice)])
    session['cart'] = sVars

    allPrices = sum(sVars[1])

    return render_template("cart.html", cartSession=session['cart'], allPrices=allPrices)

【问题讨论】:

    标签: python flask session-cookies


    【解决方案1】:

    所以,你有一个看起来像这样的列表:

    sVars = [
        ['apple', 2.12],
        ['orange', 3.13],
    ]
    

    我们只需要每个列表的第二个元素的列表,这样我们就可以sum([2.12, 3.13]) 并得到我们的结果。一种巧妙的方法是使用列表推导:

    total_price = sum([x[1] for x in sVars])
    print(total_price)
    

    这是一种(在我看来)更整洁的做法:

    total_price = 0
    for entry in sVars:
        total_price += entry[1]
    print(total_price)
    

    作为次要说明——通常 Python 建议您的变量都是小写的 svars,而 sVars 则使用 _ 表示间距,如 total_price 而不是 totalPrice,并保留 CamelCasing 作为类名,就像你和MenuItem 一样。它会让你的代码更容易被其他人查看和使用。

    【讨论】:

    • 感谢这工作!这种添加到购物篮的方法可以吗?还是有更好的方法?
    • 你的方法很好——如果我这样做,我会做一些小改动。就像我只存储引用(例如,Banana 的主键/引用是 4011)所以我会在会话中存储该 id 和数量 - 然后使用服务器查找定价/描述等。(它会处理如果您的网站更改了产品价格/描述等问题,会话仍将是旧的)
    猜你喜欢
    • 2023-01-12
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 2021-06-28
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    相关资源
    最近更新 更多