我刚刚开始学习Python来进行一些数据清理,我遇到了一个问题。我正在编写一个lambda函数,用于在Ethereum上的zkSync汇总上传递地址的事务。
import json
import requests
URL = "https://api.zksync.io/api/v0.1/account/0x2990d87e823d3cca83683207dcb2d5660debf376/history/"
def lambda_handler(event, context):
# TODO implement
#r = requests.get(url = URL)
#data = r.json()
newdata = []
#dataloaded = json.loads(data)
#for key in data:
# newdata = newdata + key
x = 1001
while x < 2000:
y = x
newURL = URL + str(y) + "/" + str(100)
r = requests.get(url = newURL)
data = r.json()
Dict = {}
i = 0
while i < 100:
Dict = {'nonce': data[i]['tx']['nonce'], 'created_at': data[i]['created_at'],'serial' : i, 'orders': data[i]['tx']['orders'] }
Dict_copy = Dict.copy()
newdata.append(Dict_copy)
i +=1
x +=100
#keyValList = ['0']
#expectedResult = [d for d in newdata if d['tx']['orders'][0]['tokenbuy'] in keyValList]
return {
'statusCode': 200,
#'body': data[0]['created_at']
'body': newdata
} API调用在历史/之后接受两个值,第一个值是我们想要查看的tx编号,第二个值是每个API调用要服务的txs数,它限制在100。因此,我创建了一个简短的脚本来解析每个调用1000个txs。但是,如果我从tx编号1000(x值)开始,而不是从0开始,查询就会崩溃。如果问题不够清楚,请帮助和道歉。
发布于 2022-06-02 14:09:48
在我们处理手头的问题之前,先先把代码弄清楚一点。
让我们不要用变量覆盖Dict类。
Dict = {} # ❌
my_dict = {} # ⭕
# or any other name you want.当我们可以使用for时,为什么要使用while循环和i+=1?
for i in range(100):
my_dict = {'nonce': data[i]['tx']['nonce'], 'created_at': data[i]['created_at'],'serial' : i, 'orders': data[i]['tx']['orders'] }
my_dict_copy = my_dict.copy() # I don't see why you're making a copy but sure.
newdata.append(my_dict_copy)外环:
for x in range(1001, 2000, 100): # start at 1001, end before 2000, jump 100
[...]在外部循环的开头,让我们使用F字符串。
newURL = URL + str(y) + "/" + str(100) # ??
newURL = f"{URL}{x}/100" # no reason to do y = x 对于手头的问题,问题的出现是因为一些条目中没有“tx”。当我检查这一点时,我是在1501年得到的,1901年也有错误。如果我们可以忽略这两个例外,那么:
import requests
URL = "https://api.zksync.io/api/v0.1/account/0x2990d87e823d3cca83683207dcb2d5660debf376/history/"
def is_valid(data_at_index_i, i):
try:
# check that all the fields are here
_ = {'nonce': data_at_index_i['tx']['nonce'], 'created_at': data_at_index_i['created_at'],'serial': i, 'orders': data_at_index_i['tx']['orders']}
except KeyError:
# we might be interested in what these entries are,
# so lets print them.
print(data_at_index_i)
print("Skipping", i, end=" ")
return 0
return 1
def lambda_handler():
# TODO implement
newdata = []
start = 1001
for x in range(start, start+1000, 100):
newURL = f"{URL}{x}/100"
r = requests.get(url = newURL)
data = r.json()
my_dict = {}
for i in range(100):
if not is_valid(data[i], i):
print(f"{x=}")\
else:
my_dict = {'nonce': data[i]['tx']['nonce'], 'created_at': data[i]['created_at'],'serial': i, 'orders': data[i]['tx']['orders']}
newdata.append(my_dict)
return {
'statusCode': 200,
#'body': data[0]['created_at']
'body': newdata
} https://stackoverflow.com/questions/72477108
复制相似问题