猿问

互联网断开后如何继续请求发布

with open("student.csv", "r") as csv_ledger:

    r = csv.DictReader(csv_ledger)

    data = [dict(d) for d in r ]

    groups = {}


    for k, g in groupby(data, lambda r: (r['name'])):

        items = []

        for i in g:

        #data processing

        try:

           post_api = requests.post(ENDPOINT_URL, json=groups, headers=headers)

        except requests.ConnectionError:

              print("Something went wrong")

        finally:

              print("resume post request")

目前,当互联网连接断开时,我的代码将无法恢复发布请求。如果我使用 try 和 exception,它就不起作用。


米琪卡哇伊
浏览 159回答 2
2回答

慕斯709654

不确定您是否可以在没有服务器端实现的情况下随意恢复,但您可以从客户端恢复。这是一个简单的阻塞示例,但您可能希望将其放入线程中。import csvimport socketfrom time import sleepimport requestsdef is_internet_on():    try:        socket.setdefaulttimeout(3)        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(('1.1.1.1', '8080'))        return True    except:        return Falsedef do_call_later(url, headers, body):    while not is_internet_on():        sleep(5)    requests.post(url, headers=headers, body=body)with open("student.csv", "r") as csv_ledger:    r = csv.DictReader(csv_ledger)    data = [dict(d) for d in r]    groups = {}    for k, g in groupby(data, lambda r: (r['name'])):        items = []        for i in g:            # data processing            pass        try:            timeout_arg = (                # first tuple value is the connection timeout,                # how long to wait before initial connection is established                1.0,                # second tuple value is the read timeout, this is how long                # the client will wait after the initial connection                # before dropping the connection because no response was sent                1.0            )            post_api = requests.post(ENDPOINT_URL, json=groups, headers=headers, timeout=timeout_arg)        except requests.ConnectionError:            do_call_later(ENDPOINT_URL, headers, groups)        finally:            print("resume post request")编辑:超时调用的文档:https : //github.com/kennethreitz/requests/blob/master/requests/api.py#L34

喵喔喔

不确定,它是否可以像这样工作。可恢复请求的思想是将数据分块发送,然后组装为后端。因此,如果中间请求失败,它可以稍后通过发送其他块来恢复。后端也应该能够接受块并组装它们看一个python库可恢复
随时随地看视频慕课网APP

相关分类

Python
我要回答