【问题标题】:Create GraphQL query in python在 python 中创建 GraphQL 查询
【发布时间】:2022-02-25 18:20:29
【问题描述】:

我想修改这个字符串:

query = """
    mutation { 
     productUpdate(input: {id: "gid://shopify/Product/463...03", title: "test", descriptionHtml: "Amazing product"}) {
       product {
         id
       }
       userErrors {
         field
         message
        }
      }
     }
  """

我试图用一个变量代替“测试”和“惊人的产品”。通常我会使用 f-strings 来执行此操作,但由于 GraphQL 括号我无法执行此操作。

有人知道如何解决这个问题吗?

非常感谢!

【问题讨论】:

    标签: python graphql


    【解决方案1】:

    您可以将花括号加倍以避开它们:

    my_title = "The Title"
    my_description = "The description"
    
    query = f"""
        mutation {{ 
         productUpdate(input: {{id: "gid://shopify/Product/463...03", title: "{my_title}", descriptionHtml: "{my_description}"}}) {{
           product {{
             id
           }}
           userErrors {{
             field
             message
            }}
          }}
         }}
      """
    

    https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals

    【讨论】:

      【解决方案2】:

      虽然 fstrings 很棒,但对于 graphql 查询,您可以使用以下格式。

      query = """
          mutation { 
           productUpdate(input: {id: "gid://shopify/Product/463...03", title: "%s", descriptionHtml: "%s"}) {
             product {
               id
             }
             userErrors {
               field
               message
              }
            }
           }
        """ % ('test', 'Amazing Product')
      
      print(query)
      

      【讨论】:

        【解决方案3】:

        您可以使用graphql-python/gql 包。支持variables

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-07-03
          • 2018-11-25
          • 2018-02-27
          • 1970-01-01
          • 2022-01-01
          • 2019-11-15
          • 2018-07-14
          • 2020-05-20
          相关资源
          最近更新 更多