首页 > 解决方案 > 使用 python 发布请求处理错误 502

问题描述

尝试构建一个简单的脚本来下载具有多个发布请求的数据。有时我会因为响应 [504] 而出现错误。

我尝试了一些尝试/除以处理此错误,但不知何故我没有捕捉到事件

我附上了没有异常处理的代码和错误图片。我知道错误来自 JSON,因为由于响应错误错误,没有要解码的数据

有任何想法吗?

import pandas as pd
import requests
import time
import os
from pandas.io.json import json_normalize

df3 = pd.DataFrame()
b = []
current_max = 0
print("downloading first 100 rows data for contract betdiceadmin")
data = {"pos": str(current_max), "offset": "100", "account_name" : "betdiceadmin"}    
request = requests.post(" https://eos.greymass.com/v1/history/get_actions", json=data)   
print(request)
jsonObj = request.json()
df = pd.DataFrame(json_normalize(jsonObj['actions']))
print("finished downloding rows " + str(current_max) +  " to " + str(max(df.account_action_seq)))
b.append(df)
current_max +=100


while max(df.account_action_seq) >= current_max:    
    print("current maximum is "+str(max(df.account_action_seq)))
    time.sleep(5)
    data = {"pos": str(current_max+1), "offset": "99", "account_name" : "betdiceadmin"}
    request = requests.post(" https://eos.greymass.com/v1/history/get_actions", json=data)
    print(request)
    jsonObj = request.json()
    df = pd.DataFrame(json_normalize(jsonObj['actions']))
    current_max +=100
    b.append(df)
    print("max from df is :" + str(max(df.account_action_seq)))


df3 = pd.concat(b, sort=True)

在此处输入图像描述

标签: postpython-requeststry-catch

解决方案


你得到了JSONDecodeError,因为你的50x响应内容不是 JSON。所以当你得到 200 时你应该运行request.json(),如果没有,请再试一次并等待更长的时间。顺便说一句,不要在 url 中添加空格。

while max(df.account_action_seq) >= current_max:    
    print("current maximum is "+str(max(df.account_action_seq)))
    time.sleep(5)
    data = {"pos": str(current_max+1), "offset": "99", "account_name" : "betdiceadmin"}
    request = requests.post("https://eos.greymass.com/v1/history/get_actions", json=data , verify=False)
    if request.status_code == 200:
        jsonObj = request.json()
        df = pd.DataFrame(json_normalize(jsonObj['actions']))
        current_max +=100
        b.append(df)
        print("max from df is :" + str(max(df.account_action_seq)))
    else:
        print("try to post again")
        continue

推荐阅读