在 Python 中构建 GraphQL 查询字符串的最佳方法 [英] Best way to construct a GraphQL query string in Python

查看:38
本文介绍了在 Python 中构建 GraphQL 查询字符串的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这样做(见标题),但它有点复杂,因为我尝试构建的字符串必须具有以下属性:

I'm trying to do this (see title), but it's a bit complicated since the string I'm trying to build has to have the following properties:

  • 多行
  • 包含花括号
  • 我想向其中注入变量

使用普通的 '''''' 多行字符串会使注入变量变得困难.使用多个 f-strings 使注入变量变得容易,但每个花括号,其中有很多,必须加倍.并且 f 必须添加到每一行.另一方面,如果我尝试使用 format,它也会被所有的花括号混淆.

Using a normal '''''' multiline string makes injecting variables difficult. Using multiple f-strings makes injecting variables easy, but every curly brace, of which there are a lot, has to be doubled. And an f has to be prepended to each line. On the other hand, if I try using format, it also gets confused by all the curly braces.

有没有我还没有考虑过的更好的方法?

Is there a better way that I haven't considered yet?

推荐答案

可以使用 """ 多行字符串方法.对于注入变量,请确保在定义字符串时使用 $ 符号并使用变量对象中的requests.post 方法的 JSON 参数.

You can use the """ multiline string method. For injecting variables, make sure to use the $ sign while defining the string and use the variables object in the JSON parameter of the requests.post method.

这是一个例子.ContactInput 是我在 GraphQL 架构中定义的类型之一.

Here is an example. ContactInput is one of the types I defined in my GraphQL schema.

query = """
  mutation ($input:[ContactInput!]!) {
    AddContacts(contacts: $input) {
      user_id
    }
  }
"""
variables = {'input': my_arrofcontacts}
r = requests.post(url, json={'query': query , 'variables': variables})

这篇关于在 Python 中构建 GraphQL 查询字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆