首页 > 解决方案 > Python - 将两个 API 值存储到变量中

问题描述

我不想将两个 API 值存储到 2 个不同的变量中,这就是我的代码的样子:

@app.route('/bflipper', methods=['POST', 'GET'])
def bFlipper():
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=[cannot show key]').json()
    products = [
        {
            "id": product["product_id"],
            "sell_price": product["sell_summary"][:1], #I want to store this
            "buy_price": product["buy_summary"][:1], # and this
            "sell_volume": product["quick_status"]["sellVolume"],
            "buy_volume": product["quick_status"]["buyVolume"],
        }
        for product in f["products"].values()
    ]
    if request.method == 'POST':
        userInput = request.form['coins']
        return render_template("flipper.html", userInput=userInput, products=products)
    else:
        return render_template("flipper.html")

我想将“sell_price”和“buy_price”存储到两个不同的变量中,然后能够将它们返回到我的 HTML 文件中,我该怎么做?

我试着做:

sellPrice = products[2] & products[3](对于 buyPrice)

但似乎不起作用。

谢谢

标签: pythonjsonapi

解决方案


变量“products”是一个包含一个 dict 对象的列表。为了访问它的第一个元素,您需要

products[0]

为了获得该元素中的密钥,您需要:

products[0]["sell_price"]

这将为您提供键“sell_price”的值。

我不确定第一个对象之后的行的意图......

for product in f["products"].values()

如果只是检查 f 中关键“产品”中的所有值,它所能做的就是。没有能力知道哪个是哪个。

但是,我不确定您要在哪里返回它,但您需要在其中构建包含它们的 html 文件。


推荐阅读