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

HAR*_*PAI 3 shopify graphql shopify-api-node shopify-api

我正在尝试通过基于标签的过滤来从 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
#       }
#     }
#   }
# }"""
Run Code Online (Sandbox Code Playgroud)

我得到的输出基本上是一个 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": []}}
Run Code Online (Sandbox Code Playgroud)

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

编辑:删除了Python标签,因为这不是Python问题,我还添加了答案,并列出了两种关于如何执行此操作的方法

dri*_*rip 5

您必须使用以下语法:

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

您可以在哪里使用OR,或者AND如果您愿意,可以包含所有标签或列出的任何标签。

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

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