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

查看:140
本文介绍了在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:

  • mulitiline
  • 包含大括号
  • 我想向其中注入物品

使用普通的''''''多行字符串会使注入变量变得困难.使用多个f字符串使注入变量变得容易,但是每个花括号都很多,都必须加倍.并且必须在每行之前添加 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?

推荐答案

您可以使用"多行字符串方法.要注入变量,请确保在定义字符串时使用$符号,并在request.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天全站免登陆