如何根据 python 中动态给出的多个不同标签获取 shopify 产品?

How to fetch shopify products based on multiple varying tags which are given dynamically in python?

我正在尝试通过基于标签的过滤从 shopify 中获取产品。标签将是动态的,不止一个,而且会发生变化。

import json
import time
import requests

API_KEY = 'xxxx'
PASSWORD = 'xxxx'
SHOP_NAME = 'xxxx'
API_VERSION = '2020-04' #change to the API version
shop_url = "https://%s:%s@%s.myshopify.com/admin/api/%s" % (API_KEY, PASSWORD, SHOP_NAME, API_VERSION)

def callShopifyGraphQL(GraphQLString, data):
    headers = {
        "X-Shopify-Storefront-Access-Token": 'xxxxxx',
        "accept":"application/json"      
    }
    response = requests.post(shop_url+'/graphql', json={'query': GraphQLString, 'variables': data}, headers=headers)
    answer = json.loads(response.text)
    return answer['data']

str1 = '0-12'
str2 = 'physical'

graphQLquery7 = """ {
  products(first:100, query:"tag:$tags") {
    edges {
      node {
        id
        tags
        title
        onlineStoreUrl
      }
    }
  }
}"""

tag = dict({
  "tags":[str1,str2]
})

resp = callShopifyGraphQL(graphQLquery7, tag)
print json.dumps(resp)


# This query works fine and gives multiple products
# graphQLquery2 = """{
#   products(first:100, query:"tag:[0-12, physical]") {
#     edges {
#       cursor
#       node {
#         id
#         tags
        
#         title
#         onlineStoreUrl
#       }
#     }
#   }
# }"""

我得到的输出基本上是一个 JSON,产品为空

{u'extensions': {u'cost': {u'requestedQueryCost': 102, u'throttleStatus': {u'restoreRate': 50.0, u'currentlyAvailable': 998, u'maximumAvailable': 1000.0}, u'actualQueryCost': 2}}, u'data': {u'products': {u'edges': []}}}
{"products": {"edges": []}}

我无法将我的标签作为查询中的变量传递。我目前正在使用 GraphQl,因为我找不到基于多个不同标签的 REST API 获取产品。

编辑:删除了 Python 标签,因为这不是 python 问题,我已经添加了答案以及关于如何做到这一点的两种方法

您必须使用流畅的语法:

{
  products(first:10, query:"tag:tag1 OR tag:tag2 OR tag:tag3"){
    edges {
      node {
        id
        tags
        title
        onlineStoreUrl
      }
    }
  }
}

如果您希望包含所有标签或列出的任何标签,可以使用 ORAND

安装 GraphiQL App 并在实施之前测试查询,这对开发过程有很大帮​​助。

有关 GraphQL 的搜索查询的更多信息,请参见此处:https://shopify.dev/concepts/about-apis/search-syntax

我终于找到了我自己问题的答案 ->

  1. 第一种方法是解决方法(或廉价的 python 技巧),它可能仅适用于问题中提到的场景。由于查询是作为字符串(多行字符串)传递的,我可以简单地使用占位符通过滥用括号 ( 和逗号 , 的行继续属性来在其中添加变量。
graphQLquery1 = """ {
  products(first:100, query:"tag:[%s, %s]") {
    edges {
      node {
        id
        tags
        title
        onlineStoreUrl
      }
    }
  }
}"""%('3+', 'personal-social')

data = None
resp = callShopifyGraphQL(graphQLquery1, data)

但是,这不是在 GraphQl 查询中使用变量的方式。

  1. 下面是在 GraphQl 中使用变量的更合适的解决方案
graphQLquery2 = """ query($tags: String){
products(first:100, query:$tags) {
    edges {
      node {
        id
        tags
        title
        onlineStoreUrl
      }
    }
  }
}"""

str1 = '0-12'
str2 = 'physical'
tags = dict({
  "tags":[str1,str2]
})
resp = callShopifyGraphQL(graphQLquery2, tags)