Python 请求中的动态负载

Dynamic payload in Python request

我在 Python 中有一个请求并希望将其动态化。这是关于有效载荷查询,如何在我的有效载荷中添加变量? 我试过使用 .format 但这不起作用。

url = "https://graphql.bitquery.io"
payload = "{\"query\":\"{\r\n  ethereum(network: bsc) {\r\n    dexTrades(\r\n      options: {limit: 100, desc: \\"tradeAmount\\"}\r\n      date: {after: \\"2021-04-30\\"}\r\n      buyCurrency: {in: \\"0xe7a39e210f067caad7992e6866beceb95b4394f7\\"}\r\n    ) {\r\n      transaction {\r\n        hash\r\n      }\r\n      date {\r\n        date\r\n      }\r\n      buyAmount\r\n      buyAmountInUsd: buyAmount(in: USD)\r\n      buyCurrency {\r\n        symbol\r\n        address\r\n        tokenId\r\n        tokenType\r\n        decimals\r\n        name\r\n      }\r\n      sellAmount\r\n      sellCurrency {\r\n        symbol\r\n        address\r\n      }\r\n      sellAmountInUsd: sellAmount(in: USD)\r\n      tradeAmount(in: USD)\r\n      smartContract {\r\n        address {\r\n          address\r\n          annotation\r\n        }\r\n        protocolType\r\n      }\r\n    }\r\n  }\r\n}\r\n\",\"variables\":{}}"
headers = {
    'X-API-KEY': '',
    'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)

我想如果我理解正确的话,graphql api 正在采用 json 格式的字符串,而您想修改 json 的查询部分。如果您将两者分开并为您希望在有效负载中更改的所需变量提供 %s 格式,它应该可以工作。

我已使用 datedesc 作为示例,但也可以使用您希望更改此方法的任何其他变量。

import json
import requests

date = '2021-04-30'
desc = 'tradeAmount'
query = """

{
  ethereum(network: bsc) {
    dexTrades(
      options: { limit: 100, desc: "%s" }
      date: { after: "%s" }
      buyCurrency: { in: "0xe7a39e210f067caad7992e6866beceb95b4394f7" }
    ) {
      transaction {
        hash
      }
      date {
        date
      }
      buyAmount
      buyAmountInUsd: buyAmount(in: USD)
      buyCurrency {
        symbol
        address
        tokenId
        tokenType
        decimals
        name
      }
      sellAmount
      sellCurrency {
        symbol
        address
      }
      sellAmountInUsd: sellAmount(in: USD)
      tradeAmount(in: USD)
      smartContract {
        address {
          address
          annotation
        }
        protocolType
      }
    }
  }
}


""" % (desc, date)

d = {'query': query, 'variables': {}}
payload = json.dumps(d)

url = "https://graphql.bitquery.io"
headers = {
    'X-API-KEY': '',
    'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)