【问题标题】:Flask: Jsonify response, then use response to call a third-party API - how to?Flask:Jsonify 响应,然后使用响应调用第三方 API - 怎么做?
【发布时间】:2021-10-24 23:20:26
【问题描述】:

我有一个 Flask 应用程序。该应用程序将一个 JSON 文件发送到使用 jsonify 对其进行解析的服务器。然后使用新解析的对象调用第三方 API。我在设置方面遇到了困难,因为我似乎无法使用 jsonified 响应对象从函数中调用第三方 API。

我的解析函数

@site.route('/data', methods=['POST']) 
def parse_request(): 
    data = request.get_json()
    print(data)
    return jsonify(success=True)
    buy(data)

print(data) 看起来像这样:

data = [{'id': '001', 'product': 'Tshirt', 'price': '9.99', 'quantity': '1'}, {'id': '002', 'product': 'Trousers', 'price': '19.99', 'quantity': '3'}, {'id': '003', 'product': 'Jacket', 'price': '29.99', 'quantity': '2'}]

如果我将 buy(data) 移动到 return 语句上方,我会收到以下错误: AttributeError: 'list' object has no attribute 'keys'.

调用第三方 API:

def buy(data):
    for key in data.keys():
      id = data[key]['id']
      quantity = data[key]['quantity']

      
      api.submit_order(
        product=product,
        quantity=quantity
      print((f"Submitted order for {quantity} piece(s) of {product}(s)"))
    return

根据我在parse_request() 中调用buy(data) 的位置,我要么得到属性错误,要么什么也没有发生。我做错了什么?

【问题讨论】:

    标签: python flask


    【解决方案1】:

    如果我将 buy(data) 移动到 return 语句上方,我会收到以下错误

    该属性错误只会在buy(data) 大于 时触发,因为一旦在函数中到达return 语句,之后不会执行任何操作。

    # This just returns 'a':
    def fn():
        return 'a'
        print ('b')
    
    # On the other hand, this prints 'b', then returns 'a'
    def fn2():
        print ('b')
        return 'a'
    

    考虑到这一点,至于实际错误:

    `AttributeError: 'list' object has no attribute 'keys'.`
    

    列表类型没有key 属性(只有字典有)。记住data 是一个字典列表。

    我想你想要的更像是:

    def buy(data):
        for row in data:
            product = row['product']
            quantity = row['quantity']      
            api.submit_order(
                product=product,
                quantity=quantity )
            print((f"Submitted order for {quantity} piece(s) of {product}(s)"))
        return
    

    【讨论】:

      【解决方案2】:

      数据是 list 的 dict 对象。您可以使用 for item in data 对其进行迭代。
      如果要遍历 dict 的键,keys 属性是必需的。

      def buy(data):
          for item in data:
              id = item['id']
              quantity = item['quantity']
      
              api.submit_order(
                  product=product,
                  quantity=quantity
              )
              print(f"Submitted order for {quantity} piece(s) of {product}(s)")
          return
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-25
        • 2019-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多