如何解决Python 请求中的动态负载
我在 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
格式,它应该可以工作。
我使用了 date
和 desc
作为示例,但也可以使用您希望更改此方法的任何其他变量。
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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。