如何在 while 循环中更新 api 调用?
How do I update an api call within a while loop?
我正在做一个简单的请求,即 returns 使用来自 polygonscan 的随机散列的来自区块链的确认号。
我遇到的问题是 while 循环,它一直循环使用相同的确认编号而不更新区块链上表示的真实编号。
例如,当哈希确认为 100 时,它将继续打印 100,而区块链确认在多边形扫描上上升。
我希望 ctc 变量在 while 循环中更新为真实确认。
from web3 import Web3
web3 = Web3(Web3.HTTPProvider(<APIKEY>))
check_txn_confirmations = web3.eth.blockNumber - web3.eth.getTransaction('0x7a0b596a664e5b56091b775d294d374364db00cab531b8dc18c70932896ccf44ec').blockNumber
ctc = check_txn_confirmations
while ctc < 260:
print("confirmations are:", ctc)
time.sleep(10)
print("waiting 10seconds..")
else:
print("confirmations are larger")
这是你想做的,也是你不应该做的:
while True:
check_txn_confirmations = web3.eth.blockNumber - web3.eth.getTransaction('0x7a0b596a664e5b56091b775d294d374364db00cab531b8dc18c70932896ccf44ec').blockNumber
ctc = check_txn_confirmations
if ctc < 260:
print("confirmations are:", ctc)
time.sleep(10)
print("waiting 10seconds..")
else:
print("confirmations are larger")
break
在 while 循环中发送请求有很多问题。
大多数 API 都有请求限制,并且请求限制通常与按使用类型付费的协议相关联。 If/when 您的程序不小心陷入了无限 while 循环,您遇到问题了。要么您的请求限制达到,要么您的余额达到 0(夸张但您明白)。
相反,我建议研究回调和异步。但对于简单的应用程序回调应该足够了。
我正在做一个简单的请求,即 returns 使用来自 polygonscan 的随机散列的来自区块链的确认号。
我遇到的问题是 while 循环,它一直循环使用相同的确认编号而不更新区块链上表示的真实编号。
例如,当哈希确认为 100 时,它将继续打印 100,而区块链确认在多边形扫描上上升。
我希望 ctc 变量在 while 循环中更新为真实确认。
from web3 import Web3
web3 = Web3(Web3.HTTPProvider(<APIKEY>))
check_txn_confirmations = web3.eth.blockNumber - web3.eth.getTransaction('0x7a0b596a664e5b56091b775d294d374364db00cab531b8dc18c70932896ccf44ec').blockNumber
ctc = check_txn_confirmations
while ctc < 260:
print("confirmations are:", ctc)
time.sleep(10)
print("waiting 10seconds..")
else:
print("confirmations are larger")
这是你想做的,也是你不应该做的:
while True:
check_txn_confirmations = web3.eth.blockNumber - web3.eth.getTransaction('0x7a0b596a664e5b56091b775d294d374364db00cab531b8dc18c70932896ccf44ec').blockNumber
ctc = check_txn_confirmations
if ctc < 260:
print("confirmations are:", ctc)
time.sleep(10)
print("waiting 10seconds..")
else:
print("confirmations are larger")
break
在 while 循环中发送请求有很多问题。
大多数 API 都有请求限制,并且请求限制通常与按使用类型付费的协议相关联。 If/when 您的程序不小心陷入了无限 while 循环,您遇到问题了。要么您的请求限制达到,要么您的余额达到 0(夸张但您明白)。
相反,我建议研究回调和异步。但对于简单的应用程序回调应该足够了。